import { motion } from 'framer-motion';
import type { CanvasComponent } from '../../types/canvas';
import { RendererWrapper, NoDataPlaceholder, type ComponentRenderContext } from './RendererWrapper';
import type { FC } from 'react';
import { Mail, Phone, Users, Calendar, MessageCircle, Clock, ArrowRight } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';

interface Props { component: CanvasComponent; ctx: ComponentRenderContext }

const URGENCY_COLORS = {
  critical: { bg: 'rgba(239,68,68,0.1)', border: 'rgba(239,68,68,0.25)', text: '#f87171', label: 'Critical' },
  high: { bg: 'rgba(251,191,36,0.1)', border: 'rgba(251,191,36,0.25)', text: '#fbbf24', label: 'High' },
  medium: { bg: 'rgba(59,130,246,0.1)', border: 'rgba(59,130,246,0.2)', text: '#60a5fa', label: 'Medium' },
  low: { bg: 'rgba(255,255,255,0.03)', border: 'rgba(255,255,255,0.07)', text: '#71717a', label: 'Low' },
};

const TYPE_ICONS: Record<string, FC<{ className?: string }>> = {
  Email: Mail,
  Call: Phone,
  Meeting: Users,
  Appointment: Calendar,
  WhatsApp: MessageCircle,
};

export function ActivityStreamRenderer({ component, ctx }: Props) {
  const rows = (component.dataRows ?? []) as Array<Record<string, unknown>>;

  if (!rows.length) return (
    <RendererWrapper component={component} ctx={ctx} minHeight={320}>
      <NoDataPlaceholder message="No activities found matching your filters." />
    </RendererWrapper>
  );

  const hasUrgency = rows.some((r) => r.urgency !== undefined);
  const hasTimeline = rows.some((r) => r.type !== undefined && r.date !== undefined);

  return (
    <RendererWrapper component={component} ctx={ctx} minHeight={340}>
      {hasTimeline ? (
        // Timeline layout
        <div className="relative space-y-4 pl-6">
          <div className="absolute left-[17px] top-1 bottom-4 w-[2px] bg-gradient-to-b from-blue-500 via-cyan-500/40 to-transparent" />
          {rows.map((row, i) => {
            const TypeIcon = TYPE_ICONS[String(row.type ?? '')] ?? Calendar;
            return (
              <motion.div
                key={i}
                initial={{ opacity: 0, x: -8 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: i * 0.07 }}
                className="relative pl-5 group cursor-pointer"
              >
                <div className="absolute -left-[3px] top-1.5 h-3.5 w-3.5 rounded-full bg-zinc-950 border-2 border-blue-400 shadow-[0_0_10px_rgba(59,130,246,0.6)]" />
                <div
                  className="p-3.5 rounded-xl"
                  style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="flex items-center gap-2 mb-1">
                        <TypeIcon className="w-3.5 h-3.5 text-blue-400" />
                        <span className="text-xs font-semibold uppercase tracking-wider text-blue-300">
                          {String(row.type ?? '')}
                        </span>
                      </div>
                      <p className="text-sm text-zinc-200 font-medium">
                        {String(row.title ?? row.summary ?? '')}
                      </p>
                      {row.actor !== undefined && (
                        <p className="text-xs text-zinc-500 mt-0.5">{String(row.actor)}</p>
                      )}
                    </div>
                    <span className="text-xs text-zinc-600 font-mono whitespace-nowrap flex-shrink-0">
                      {String(row.date ?? row.when ?? '')}
                    </span>
                  </div>
                </div>
              </motion.div>
            );
          })}
        </div>
      ) : hasUrgency ? (
        // Follow-up queue layout
        <div className="space-y-2">
          {rows.map((row, i) => {
            const urgency = String(row.urgency ?? 'low') as keyof typeof URGENCY_COLORS;
            const uc = URGENCY_COLORS[urgency] ?? URGENCY_COLORS.low;
            const hoursAgo = Number(row.last_contact_hours_ago ?? 0);

            return (
              <motion.div
                key={i}
                initial={{ opacity: 0, y: 4 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.06 }}
                className="flex items-center gap-3 p-3 rounded-xl group cursor-pointer"
                style={{ background: uc.bg, border: `1px solid ${uc.border}` }}
              >
                <Avatar className="h-9 w-9 border border-white/10 flex-shrink-0">
                  <AvatarImage src={String(row.avatar ?? '')} />
                  <AvatarFallback className="bg-zinc-800 text-zinc-400 text-xs">
                    {String(row.name ?? '').slice(0, 2)}
                  </AvatarFallback>
                </Avatar>
                <div className="min-w-0 flex-1">
                  <p className="text-sm font-medium text-zinc-100 truncate">{String(row.name ?? '')}</p>
                  <div className="flex items-center gap-2 mt-0.5">
                    <Clock className="w-3 h-3" style={{ color: uc.text }} />
                    <span className="text-xs" style={{ color: uc.text }}>
                      {hoursAgo}h without contact
                    </span>
                    <span className="text-xs text-zinc-500">• {String(row.assigned_broker ?? '')}</span>
                  </div>
                </div>
                <div className="flex items-center gap-2 flex-shrink-0">
                  <Badge
                    className="text-[10px] h-5 px-1.5"
                    style={{ background: uc.bg, color: uc.text, border: `1px solid ${uc.border}` }}
                  >
                    {uc.label}
                  </Badge>
                  <span className="text-xs text-zinc-500 font-mono">QD:{Number(row.qd_score ?? 0).toFixed(0)}</span>
                  <ArrowRight className="w-4 h-4 text-zinc-600 group-hover:text-zinc-400 transition-colors" />
                </div>
              </motion.div>
            );
          })}
        </div>
      ) : (
        <NoDataPlaceholder />
      )}
    </RendererWrapper>
  );
}
