import { motion } from 'framer-motion';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import type { CanvasComponent } from '../../types/canvas';
import { RendererWrapper, NoDataPlaceholder, type ComponentRenderContext } from './RendererWrapper';
import { Trophy } from 'lucide-react';
import { useCurrency } from '@/store/useCurrencyStore';

interface Props { component: CanvasComponent; ctx: ComponentRenderContext }

export function TableRenderer({ component, ctx }: Props) {
  const { formatText } = useCurrency();
  const rows = (component.dataRows ?? []) as Array<Record<string, unknown>>;
  const columns = (component.visualizationParameters as { columns?: string[] }).columns
    ?? (rows[0] ? Object.keys(rows[0]).filter((k) => !['avatar', 'rank'].includes(k)) : []);

  if (!rows.length) return (
    <RendererWrapper component={component} ctx={ctx} minHeight={260}>
      <NoDataPlaceholder />
    </RendererWrapper>
  );

  const hasAvatar = rows.some((r) => r.avatar);
  const hasRank = rows.some((r) => r.rank !== undefined);

  return (
    <RendererWrapper component={component} ctx={ctx} minHeight={280}>
      <div className="overflow-hidden rounded-xl" style={{ border: '1px solid rgba(255,255,255,0.06)' }}>
        {/* Header */}
        <div
          className="grid gap-3 px-4 py-2.5 text-[10px] uppercase tracking-widest text-zinc-500"
          style={{
            gridTemplateColumns: hasRank
              ? `28px ${hasAvatar ? '40px' : ''} 1fr repeat(${columns.filter((c) => !['name', 'avatar', 'rank'].includes(c)).length}, minmax(80px, 1fr))`
              : `${hasAvatar ? '40px' : ''} 1fr repeat(${columns.filter((c) => !['name', 'avatar', 'rank'].includes(c)).length}, minmax(80px, 1fr))`,
            background: 'rgba(255,255,255,0.03)',
            borderBottom: '1px solid rgba(255,255,255,0.06)',
          }}
        >
          {hasRank && <span>#</span>}
          {hasAvatar && <span />}
          {columns.map((c) => (
            <span key={c} className="capitalize">{c.replace(/_/g, ' ')}</span>
          ))}
        </div>

        {/* Rows */}
        <div className="divide-y divide-white/[0.04]">
          {rows.map((row, i) => (
            <motion.div
              key={i}
              initial={{ opacity: 0, x: -8 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: i * 0.05 }}
              className="grid gap-3 px-4 py-3 items-center hover:bg-white/[0.02] transition-colors group cursor-pointer"
              style={{
                gridTemplateColumns: hasRank
                  ? `28px ${hasAvatar ? '40px' : ''} 1fr repeat(${columns.filter((c) => !['name', 'avatar', 'rank'].includes(c)).length}, minmax(80px, 1fr))`
                  : `${hasAvatar ? '40px' : ''} 1fr repeat(${columns.filter((c) => !['name', 'avatar', 'rank'].includes(c)).length}, minmax(80px, 1fr))`,
              }}
            >
              {hasRank && (
                <div className="flex items-center justify-center">
                  {Number(row.rank) === 1 ? (
                    <Trophy className="w-4 h-4 text-amber-400" />
                  ) : (
                    <span className="text-xs text-zinc-500 font-mono">{String(row.rank)}</span>
                  )}
                </div>
              )}
              {hasAvatar && (
                <Avatar className="h-8 w-8 border border-white/10">
                  <AvatarImage src={String(row.avatar ?? '')} />
                  <AvatarFallback className="bg-zinc-800 text-zinc-400 text-xs">
                    {String(row.name ?? '').slice(0, 2)}
                  </AvatarFallback>
                </Avatar>
              )}
              {columns.map((col) => (
                <div key={col} className="min-w-0">
                  {col === 'name' ? (
                    <span className="text-sm text-zinc-100 font-medium group-hover:text-blue-100 transition-colors truncate block">
                      {formatText(String(row[col] ?? '—'))}
                    </span>
                  ) : (
                    <span className="text-sm text-zinc-300 font-mono truncate block">
                      {formatText(String(row[col] ?? '—'))}
                    </span>
                  )}
                </div>
              ))}
            </motion.div>
          ))}
        </div>
      </div>
    </RendererWrapper>
  );
}
