'use client';

import { useState, useEffect } from 'react';
import { TrendingUp, AlertCircle, Loader2 } from 'lucide-react';
import {
  AreaChart, Area, BarChart, Bar, LineChart, Line,
  XAxis, YAxis, CartesianGrid, Tooltip,
} from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import { getAdminAnalytics } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface AnalyticsData {
  analytics: {
    totalConversations: number; todayConversations: number;
    totalApiCalls: number; avgCallDuration: number;
    totalVoiceCalls: number; escalationRate: number; escalatedCount: number;
  };
  conversationTrend: { date: string; conversations: number }[];
  latencyTrend: { date: string; avgDuration: number; callCount: number }[];
  errorBreakdown: { type: string; count: number }[];
}

export default function PlatformAnalyticsPage() {
  const { t } = useLanguage();
  usePageHeader(t('admin.platformAnalytics.pageTitle', "Platform Analytics"), t('admin.platformAnalytics.pageDesc', "Usage trends and performance"));
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getAdminAnalytics()
      .then(setData)
      .catch(() => setData(null))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <>
        <div className="flex items-center justify-center py-20">
          <Loader2 className="animate-spin" size={32} />
        </div>
      </>
    );
  }

  const a = data?.analytics;
  const kpis = [
    { label: t('admin.platformAnalytics.totalConversations', 'Total Conversations'), value: (a?.totalConversations ?? 0).toLocaleString() },
    { label: t('admin.platformAnalytics.todayConversations', 'Today\'s Conversations'), value: (a?.todayConversations ?? 0).toLocaleString() },
    { label: t('admin.platformAnalytics.totalApiCalls', 'Total API Calls'), value: (a?.totalApiCalls ?? 0).toLocaleString() },
    { label: t('admin.platformAnalytics.avgCallDuration', 'Avg Call Duration'), value: `${a?.avgCallDuration ?? 0}s` },
    { label: t('admin.platformAnalytics.voiceCalls14d', 'Voice Calls (14d)'), value: (a?.totalVoiceCalls ?? 0).toLocaleString() },
    { label: t('admin.platformAnalytics.escalationRate', 'Escalation Rate'), value: `${a?.escalationRate ?? 0}%` },
  ];

  return (
    <>
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.platformAnalytics.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.platformAnalytics.adminPanelDesc', 'Platform-wide performance metrics')}</span>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        {kpis.map(kpi => (
          <div key={kpi.label} className="metric-card">
            <div className="flex items-center justify-between mb-2">
              <TrendingUp size={16} style={{ color: 'hsl(var(--success))' }} />
            </div>
            <p className="text-2xl font-bold tabular-nums" style={{ color: 'hsl(var(--foreground))' }}>{kpi.value}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{kpi.label}</p>
          </div>
        ))}
      </div>

      <div className="card p-5 mb-5">
        <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.platformAnalytics.convTrendTitle', 'Conversation Trend (Last 14 Days)')}</h3>
        {(data?.conversationTrend?.length ?? 0) > 0 ? (
          <SafeChart height={220}>
            <AreaChart data={data!.conversationTrend} margin={{ top: 5, right: 10, left: -10, bottom: 0 }}>
              <defs>
                <linearGradient id="convGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0.15} />
                  <stop offset="95%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" />
              <XAxis dataKey="date" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
              <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} />
              <Area type="monotone" dataKey="conversations" stroke="hsl(22, 89%, 48%)" strokeWidth={2} fill="url(#convGrad)" name={t('admin.platformAnalytics.chartConversations', "Conversations")} />
            </AreaChart>
          </SafeChart>
        ) : (
          <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.platformAnalytics.noConvData', 'No conversation data yet')}</p>
        )}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <div className="card p-5">
          <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.platformAnalytics.avgCallDurationTitle', 'Avg Call Duration (Last 14 Days)')}</h3>
          {(data?.latencyTrend?.length ?? 0) > 0 ? (
            <SafeChart height={200}>
              <LineChart data={data!.latencyTrend} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" />
                <XAxis dataKey="date" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
                <YAxis tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} unit="s" />
                <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} />
                <Line type="monotone" dataKey="avgDuration" stroke="hsl(22, 89%, 48%)" strokeWidth={2} dot={false} name={t('admin.platformAnalytics.chartAvgDuration', "Avg Duration (s)")} />
              </LineChart>
            </SafeChart>
          ) : (
            <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.platformAnalytics.noCallData', 'No call data yet')}</p>
          )}
        </div>

        <div className="card p-5">
          <div className="flex items-center gap-2 mb-4">
            <AlertCircle size={16} style={{ color: 'hsl(var(--danger))' }} />
            <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.platformAnalytics.convStatusTitle', 'Conversation Status Breakdown (14d)')}</h3>
          </div>
          {(data?.errorBreakdown?.length ?? 0) > 0 ? (
            <SafeChart height={200}>
              <BarChart data={data!.errorBreakdown} layout="vertical" margin={{ top: 0, right: 10, left: 30, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" horizontal={false} />
                <XAxis type="number" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} />
                <YAxis type="category" dataKey="type" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)' }} axisLine={false} tickLine={false} width={120} />
                <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} />
                <Bar dataKey="count" fill="hsl(22, 89%, 48%)" radius={[0, 4, 4, 0]} name={t('admin.platformAnalytics.chartCount', "Count")} />
              </BarChart>
            </SafeChart>
          ) : (
            <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.platformAnalytics.noConvData', 'No conversation data yet')}</p>
          )}
        </div>
      </div>
    </>
  );
}
