'use client';

import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import type { ChannelPoint, DashboardPeriod } from '@client/api/analytics';
import { useLanguage } from '@client/contexts/LanguageContext';

const CustomTooltip = ({ active, payload, label, t }: any) => {
  if (active && payload && payload.length) {
    const total = payload.reduce((sum: number, p: any) => sum + p.value, 0);
    return (
      <div className="rounded-xl px-4 py-3 shadow-lg" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', boxShadow: 'var(--shadow-lg)' }}>
        <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{label}</p>
        {payload.map((entry: any, i: number) => (
          <div key={i} className="flex items-center gap-2 text-sm">
            <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: entry.fill }} />
            <span style={{ color: 'hsl(var(--foreground-secondary))' }}>{entry.name}:</span>
            <span className="font-semibold font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{entry.value}</span>
          </div>
        ))}
        <div className="mt-1.5 pt-1.5" style={{ borderTop: '1px solid hsl(var(--border))' }}>
          <div className="flex justify-between text-xs">
            <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.total', 'Total')}</span>
            <span className="font-semibold font-mono tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{total}</span>
          </div>
        </div>
      </div>
    );
  }
  return null;
};

interface ChannelBreakdownChartProps {
  data: ChannelPoint[];
  loading: boolean;
  period: DashboardPeriod;
}

export default function ChannelBreakdownChart({ data, loading, period }: ChannelBreakdownChartProps) {
  const { t } = useLanguage();
  const hasData = data.length > 0 && data.some(d => d.voice > 0 || d.chat > 0);

  const PERIOD_SUBTITLE: Record<DashboardPeriod, string> = {
    today: t('dashboard.voiceVsChatToday', 'Voice vs Chat — Today'),
    '7days': t('dashboard.voiceVsChat7Days', 'Voice vs Chat — Last 7 Days'),
    month: t('dashboard.voiceVsChatMonth', 'Voice vs Chat — This Month'),
    lifetime: t('dashboard.voiceVsChatLifetime', 'Voice vs Chat — All Time'),
  };

  return (
    <div className="card p-5" style={{ height: '100%' }}>
      <div className="flex items-center justify-between mb-5">
        <div>
          <p className="section-label">{t('dashboard.channelBreakdown', 'Channel Breakdown')}</p>
          <p className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{PERIOD_SUBTITLE[period]}</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-1.5">
            <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: 'hsl(var(--primary))' }} />
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.voice', 'Voice')}</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-2.5 h-2.5 rounded-full" style={{ backgroundColor: 'hsl(210, 100%, 40%)' }} />
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.chat', 'Chat')}</span>
          </div>
        </div>
      </div>

      {loading ? (
        <div className="h-[200px] flex items-center justify-center">
          <div className="animate-pulse text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.loadingChartData', 'Loading chart data...')}</div>
        </div>
      ) : !hasData ? (
        <div className="h-[200px] flex flex-col items-center justify-center text-center">
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.noChannelData', 'No channel data yet')}</p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.channelBreakdownAppear', 'Channel breakdown will appear as orders come in')}</p>
        </div>
      ) : (
        <SafeChart height={200}>
          <BarChart data={data} margin={{ top: 4, right: 4, bottom: 0, left: -10 }} barCategoryGap="30%">
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" vertical={false} />
            <XAxis dataKey="day" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)', fontFamily: 'DM Sans' }} tickLine={false} axisLine={false} />
            <YAxis tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)', fontFamily: 'DM Sans' }} tickLine={false} axisLine={false} />
            <Tooltip content={<CustomTooltip t={t} />} cursor={{ fill: 'hsl(220, 9%, 96%)' }} />
            <Bar dataKey="voice" name={t('dashboard.voice', 'Voice')} fill="hsl(22, 89%, 48%)" radius={[4, 4, 0, 0]} />
            <Bar dataKey="chat" name={t('dashboard.chat', 'Chat')} fill="hsl(210, 100%, 40%)" radius={[4, 4, 0, 0]} />
          </BarChart>
        </SafeChart>
      )}
    </div>
  );
}
