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

interface Props { component: CanvasComponent; ctx: ComponentRenderContext }

interface PipelineRow {
  stage: string;
  count: number;
  value?: number;
  leads?: Array<{ id: string; name: string; company: string; value: string; avatar?: string }>;
}

const STAGE_COLORS: Record<string, string> = {
  'New Leads': '#3B82F6',
  'Qualified': '#22D3EE',
  'Proposal Sent': '#A78BFA',
  'Negotiation': '#F59E0B',
  'Closed': '#34D399',
};

export function PipelineBoardRenderer({ component, ctx }: Props) {
  const { formatAmount, formatText } = useCurrency();
  const rows = (component.dataRows ?? []) as unknown as PipelineRow[];

  if (!rows.length) return (
    <RendererWrapper component={component} ctx={ctx} minHeight={360}>
      <NoDataPlaceholder message="No pipeline data available." />
    </RendererWrapper>
  );

  return (
    <RendererWrapper component={component} ctx={ctx} minHeight={380}>
      <div className="grid gap-3" style={{ gridTemplateColumns: `repeat(${Math.min(rows.length, 4)}, 1fr)` }}>
        {rows.map((stageData, si) => {
          const color = STAGE_COLORS[stageData.stage] ?? '#60a5fa';
          return (
            <motion.div
              key={stageData.stage}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: si * 0.07 }}
              className="flex flex-col rounded-xl p-3"
              style={{ background: 'rgba(255,255,255,0.025)', border: '1px solid rgba(255,255,255,0.07)' }}
            >
              {/* Stage header */}
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full" style={{ background: color, boxShadow: `0 0 8px ${color}` }} />
                  <span className="text-xs font-medium uppercase tracking-wider text-zinc-400">{stageData.stage}</span>
                </div>
                <Badge
                  variant="outline"
                  className="border-white/10 bg-white/5 text-zinc-400 text-[10px] h-5 px-1.5"
                >
                  {stageData.count}
                </Badge>
              </div>

              {/* Lead cards */}
              <div className="space-y-2 flex-1">
                {(stageData.leads ?? []).slice(0, 3).map((lead, li) => (
                  <motion.div
                    key={lead.id}
                    initial={{ opacity: 0, x: -4 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: si * 0.07 + li * 0.05 }}
                    className="group p-2.5 rounded-lg relative"
                    style={{
                      background: 'rgba(255,255,255,0.02)',
                      border: '1px solid rgba(255,255,255,0.05)',
                      cursor: 'pointer',
                    }}
                    whileHover={{ background: `${color}12`, borderColor: `${color}30` }}
                  >
                    {/* Accent bar */}
                    <div
                      className="absolute left-0 top-2 bottom-2 w-0.5 rounded-r-full opacity-0 group-hover:opacity-100 transition-opacity"
                      style={{ background: color }}
                    />
                    <div className="flex items-center gap-2 pl-1">
                      <Avatar className="h-7 w-7 border border-white/10 flex-shrink-0">
                        <AvatarImage src={lead.avatar} />
                        <AvatarFallback className="bg-zinc-800 text-zinc-400 text-[10px]">
                          {lead.name.slice(0, 2)}
                        </AvatarFallback>
                      </Avatar>
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-medium text-zinc-100 truncate">{lead.name}</p>
                        <p className="text-[10px] text-zinc-500 truncate">{formatText(lead.value)}</p>
                      </div>
                    </div>
                  </motion.div>
                ))}

                {stageData.count > 3 && (
                  <p className="text-[10px] text-zinc-600 text-center pt-1">
                    +{stageData.count - 3} more
                  </p>
                )}
              </div>

              {/* Stage total */}
              {stageData.value !== undefined && (
                <div className="mt-2 pt-2" style={{ borderTop: '1px solid rgba(255,255,255,0.06)' }}>
                  <p className="text-[10px] text-zinc-600 uppercase tracking-wider">Total</p>
                  <p className="text-sm font-semibold text-zinc-200">
                    {formatAmount(stageData.value, { compact: true })}
                  </p>
                </div>
              )}
            </motion.div>
          );
        })}
      </div>
    </RendererWrapper>
  );
}
