'use client';

import { TrendingUp, TrendingDown, Bot, ShoppingBag, CalendarDays, AlertTriangle, Target, DollarSign } from 'lucide-react';
import {
  RadialBarChart, RadialBar, PolarAngleAxis,
} from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import type { DashboardStats, DashboardPeriod } from '@client/api/analytics';
import { useCurrency } from '@client/hooks/useCurrency';
import { useLanguage } from '@client/contexts/LanguageContext';

interface KPICardProps {
  label: string;
  value: string;
  subValue?: string;
  trend?: { value: string; direction: 'up' | 'down'; isPositive: boolean };
  icon: React.ReactNode;
  iconBg: string;
  iconColor: string;
  variant?: 'default' | 'hero' | 'alert' | 'success';
  colSpan?: number;
  children?: React.ReactNode;
}

function KPICard({ label, value, subValue, trend, icon, iconBg, iconColor, variant = 'default', colSpan = 1, children }: KPICardProps) {
  const variantStyles: Record<string, React.CSSProperties> = {
    default: { backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' },
    hero: { backgroundColor: 'hsl(var(--surface))', border: '2px solid hsl(var(--primary))', boxShadow: '0 0 0 4px hsl(22, 89%, 48%, 0.08)' },
    alert: { backgroundColor: 'hsl(var(--danger-bg))', border: '1px solid hsl(var(--danger-border))' },
    success: { backgroundColor: 'hsl(var(--success-bg))', border: '1px solid hsl(var(--success-border))' },
  };

  return (
    <div className={`metric-card flex flex-col ${colSpan === 2 ? 'col-span-2' : 'col-span-1'}`} style={variantStyles[variant]}>
      <div className="flex items-start justify-between mb-3">
        <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: iconBg, color: iconColor }}>
          {icon}
        </div>
        {trend && (
          <div className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full" style={{ backgroundColor: trend.isPositive ? 'hsl(var(--success-bg))' : 'hsl(var(--danger-bg))', color: trend.isPositive ? 'hsl(var(--success))' : 'hsl(var(--danger))' }}>
            {trend.direction === 'up' ? <TrendingUp size={11} /> : <TrendingDown size={11} />}
            {trend.value}
          </div>
        )}
      </div>
      <div className="flex-1">
        <p className="section-label mb-1" style={{ color: variant === 'alert' ? 'hsl(var(--danger))' : variant === 'success' ? 'hsl(var(--success))' : undefined }}>
          {label}
        </p>
        <p className="text-3xl font-bold tabular-nums font-mono leading-none" style={{ color: variant === 'hero' ? 'hsl(var(--primary))' : variant === 'alert' ? 'hsl(var(--danger))' : variant === 'success' ? 'hsl(var(--success))' : 'hsl(var(--foreground))' }}>
          {value}
        </p>
        {subValue && <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{subValue}</p>}
      </div>
      {children && <div className="mt-3">{children}</div>}
    </div>
  );
}

function ResolutionGauge({ rate, t }: { rate: number; t: (key: string, fallback: string) => string }) {
  const data = [{ value: rate, fill: 'hsl(22, 89%, 48%)' }];
  return (
    <div className="flex items-center gap-4">
      <SafeChart width={80} height={80}>
        <RadialBarChart cx="50%" cy="50%" innerRadius="65%" outerRadius="100%" startAngle={90} endAngle={-270} data={data}>
          <PolarAngleAxis type="number" domain={[0, 100]} tick={false} />
          <RadialBar dataKey="value" cornerRadius={6} background={{ fill: 'hsl(220, 13%, 91%)' }} />
        </RadialBarChart>
      </SafeChart>
      <div>
        <p className="text-4xl font-bold font-mono tabular-nums" style={{ color: 'hsl(var(--primary))' }}>{rate}%</p>
        <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.ofAllConversations', 'of all conversations')}</p>
        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.fullyResolvedByAi', 'fully resolved by AI')}</p>
      </div>
    </div>
  );
}

function LoadingSkeleton() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-4 2xl:grid-cols-4 gap-4">
      {Array.from({ length: 8 }).map((_, i) => (
        <div key={i} className={`metric-card animate-pulse ${i === 0 ? 'col-span-1 sm:col-span-2 lg:col-span-2' : 'col-span-1'}`}>
          <div className="h-9 w-9 rounded-lg bg-gray-200 mb-3" />
          <div className="h-4 w-24 bg-gray-200 rounded mb-2" />
          <div className="h-8 w-16 bg-gray-200 rounded" />
        </div>
      ))}
    </div>
  );
}

interface KPIBentoGridProps {
    stats: import('@client/api/analytics').DashboardStats | null;
    loading: boolean;
    period: import('@client/api/analytics').DashboardPeriod;
  }

  export default function KPIBentoGrid({ stats, loading, period }: KPIBentoGridProps) {
  const { t } = useLanguage();
  const { format: fc } = useCurrency();

  if (loading || !stats) return <LoadingSkeleton />;

  const PERIOD_LABEL: Record<DashboardPeriod, string> = {
    today: t('period.today', 'Today'),
    '7days': t('period.7days', '7 Days'),
    month: t('period.thisMonth', 'This Month'),
    lifetime: t('period.allTime', 'All Time'),
  };

  const pl = PERIOD_LABEL[period];

  const periodConvs = parseInt(stats.conversations.period_conversations ?? '0', 10);
  const periodAiConvs = parseInt(stats.conversations.period_ai_conversations ?? '0', 10);
  const periodResolvedConvs = parseInt(stats.conversations.period_resolved_conversations ?? '0', 10);
  const humanConvs = parseInt(stats.conversations.human_conversations ?? '0', 10);
  const periodHumanConvs = parseInt(stats.conversations.period_human_conversations ?? '0', 10);
  const resolutionRate = periodConvs > 0 ? Math.round(((periodAiConvs + periodResolvedConvs) / periodConvs) * 100) : 0;
  const escalationRate = periodConvs > 0 ? parseFloat(((periodHumanConvs / periodConvs) * 100).toFixed(1)) : 0;
  const avgConfidence = parseFloat(parseFloat(stats.conversations.period_avg_confidence ?? '0').toFixed(1));

  const periodOrders = parseInt(stats.orders.period_orders ?? '0', 10);
  const voiceOrders = parseInt(stats.orders.period_voice_orders ?? '0', 10);
  const chatOrders = parseInt(stats.orders.period_chat_orders ?? '0', 10);
  const completedOrders = parseInt(stats.orders.period_completed_orders ?? '0', 10);
  const periodRevenue = parseFloat(stats.revenue.period_revenue ?? '0');

  const periodBookings = parseInt(stats.bookings.period_bookings ?? '0', 10);
  const confirmedBookings = parseInt(stats.bookings.period_confirmed_bookings ?? '0', 10);
  const tomorrowBookings = parseInt(stats.bookings.tomorrow_bookings ?? '0', 10);

  const bookingSubValue = period === 'today'
    ? t('dashboard.bookingSubToday', `${confirmedBookings} confirmed · ${tomorrowBookings} tomorrow`, { confirmed: confirmedBookings, tomorrow: tomorrowBookings })
    : t('dashboard.bookingSubOther', `${confirmedBookings} confirmed`, { confirmed: confirmedBookings });

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 xl:grid-cols-4 2xl:grid-cols-4 gap-4">
      <div className="col-span-1 sm:col-span-2 lg:col-span-2 metric-card" style={{ border: '2px solid hsl(var(--primary))', boxShadow: '0 0 0 4px hsl(22, 89%, 48%, 0.08)' }}>
        <div className="flex items-start justify-between mb-3">
          <div>
            <p className="section-label">{t('dashboard.agentResolutionRate', 'Agent Resolution Rate')}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.aiResolvedNoHandoff', 'AI-resolved without human handoff')}</p>
          </div>
          <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}>
            <Bot size={18} />
          </div>
        </div>
        <ResolutionGauge rate={resolutionRate} t={t} />
        <div className="grid grid-cols-3 gap-3 mt-4 pt-4" style={{ borderTop: '1px solid hsl(var(--border))' }}>
          <div>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.aiConfidence', 'AI Confidence')}</p>
            <p className="text-sm font-semibold font-mono mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{avgConfidence}%</p>
          </div>
          <div>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.escalationRate', 'Escalation Rate')}</p>
            <p className="text-sm font-semibold font-mono mt-0.5" style={{ color: 'hsl(var(--warning))' }}>{escalationRate}%</p>
          </div>
          <div>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.needsAgent', 'Needs Agent')}</p>
            <p className="text-sm font-semibold font-mono mt-0.5" style={{ color: 'hsl(var(--danger))' }}>{humanConvs}</p>
          </div>
        </div>
      </div>

      <KPICard
        label={t('dashboard.aiOrdersWithPeriod', `AI Orders — ${pl}`, { period: pl })}
        value={String(periodOrders)}
        subValue={t('dashboard.ordersSubValue', `${voiceOrders} via voice · ${chatOrders} via chat`, { voice: voiceOrders, chat: chatOrders })}
        icon={<ShoppingBag size={18} />}
        iconBg="hsl(var(--primary-light))"
        iconColor="hsl(var(--primary))"
      />

      <KPICard
        label={t('dashboard.reservationsWithPeriod', `Reservations — ${pl}`, { period: pl })}
        value={String(periodBookings)}
        subValue={bookingSubValue}
        icon={<CalendarDays size={18} />}
        iconBg="hsl(var(--info-bg))"
        iconColor="hsl(var(--info))"
      />

      <KPICard
        label={t('dashboard.revenueViaAiWithPeriod', `Revenue via AI — ${pl}`, { period: pl })}
        value={fc(periodRevenue)}
        subValue={t('dashboard.totalOrderValueProcessed', 'Total order value processed')}
        icon={<DollarSign size={18} />}
        iconBg="hsl(var(--success-bg))"
        iconColor="hsl(var(--success))"
      />

      <KPICard
        label={t('dashboard.activeEscalations', 'Active Escalations')}
        value={String(humanConvs)}
        subValue={t('dashboard.convsNeedingAttention', 'Conversations needing human attention')}
        variant={humanConvs > 0 ? 'alert' : 'success'}
        icon={<AlertTriangle size={18} />}
        iconBg={humanConvs > 0 ? 'hsl(var(--danger-bg))' : 'hsl(var(--success-bg))'}
        iconColor={humanConvs > 0 ? 'hsl(var(--danger))' : 'hsl(var(--success))'}
      />

      <KPICard
        label={t('dashboard.ordersCompletedWithPeriod', `Orders Completed — ${pl}`, { period: pl })}
        value={String(completedOrders)}
        subValue={t('dashboard.fullyFulfilledOrders', 'Fully fulfilled orders')}
        variant="success"
        icon={<Target size={18} />}
        iconBg="hsl(var(--success-bg))"
        iconColor="hsl(var(--success))"
      />

      <KPICard
        label={t('dashboard.aiAccuracy', 'AI Accuracy')}
        value={`${avgConfidence}%`}
        subValue={t('dashboard.avgConfidenceWithPeriod', `Average confidence — ${pl}`, { period: pl })}
        icon={<Bot size={18} />}
        iconBg="hsl(var(--primary-light))"
        iconColor="hsl(var(--primary))"
      />
    </div>
  );
}
