'use client';

import { useState, useEffect } from 'react';
import { TrendingUp, Store, DollarSign, Bot, Loader2 } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import { getAdminDashboard } from '@client/api/admin';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

interface DashboardData {
  stats: { mrr: number; activeRestaurants: number; totalConversations: number; churnRate: number };
  mrrHistory: { month: string; mrr: number }[];
  recentRestaurants: { name: string; plan: string; status: string; createdAt: string; mrr: number }[];
}

function formatTimeSince(dateStr: string, t: TFn): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  if (days === 0) return t('common.today', 'Today');
  if (days === 1) return t('common.oneDayAgo', '1 day ago');
  const weeks = Math.floor(days / 7);
  const months = Math.floor(days / 30);
  if (days < 7) return t('common.daysAgo', '{{n}} days ago', { n: days });
  if (days < 30) return t('common.weeksAgo', '{{n}} week{{s}} ago', { n: weeks, s: weeks > 1 ? 's' : '' });
  return t('common.monthsAgo', '{{n}} month{{s}} ago', { n: months, s: months > 1 ? 's' : '' });
}

export default function AdminDashboardPage() {
  const { t } = useLanguage();
  usePageHeader(t('admin.dashboard', 'Admin Dashboard'), t('admin.platformMetrics', 'Platform-wide metrics and health'));
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getAdminDashboard()
      .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 stats = data?.stats;
  const kpis = [
    { label: t('admin.mrr', 'Monthly Recurring Revenue'), value: `$${(stats?.mrr ?? 0).toLocaleString()}`, icon: <DollarSign size={18} /> },
    { label: t('admin.activeRestaurants', 'Active Restaurants'), value: String(stats?.activeRestaurants ?? 0), icon: <Store size={18} /> },
    { label: t('admin.totalConversations', 'Total AI Conversations'), value: (stats?.totalConversations ?? 0).toLocaleString(), icon: <Bot size={18} /> },
    { label: t('admin.churnRate', 'Churn Rate'), value: `${stats?.churnRate ?? 0}%`, icon: <TrendingUp size={18} /> },
  ];

  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.adminPanel', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.viewingPlatformData', 'You are viewing platform-wide data as SaaS owner')}</span>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        {kpis.map(kpi => (
          <div key={kpi.label} className="metric-card">
            <div className="flex items-center justify-between mb-3">
              <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
                {kpi.icon}
              </div>
            </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.mrrGrowth', 'MRR Growth')}</h3>
        {(data?.mrrHistory?.length ?? 0) > 0 ? (
          <SafeChart height={220}>
            <AreaChart data={data!.mrrHistory} margin={{ top: 5, right: 10, left: -10, bottom: 0 }}>
              <defs>
                <linearGradient id="mrrGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="hsl(231, 40%, 14%)" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="hsl(231, 40%, 14%)" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" />
              <XAxis dataKey="month" 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} tickFormatter={v => `$${(v/1000).toFixed(0)}k`} />
              <Tooltip contentStyle={{ borderRadius: '10px', fontSize: 12 }} formatter={(v: number) => [`${v.toLocaleString()}`, t('common.mrr', 'MRR')]} />
              <Area type="monotone" dataKey="mrr" stroke="hsl(231, 40%, 14%)" strokeWidth={2.5} fill="url(#mrrGrad)" />
            </AreaChart>
          </SafeChart>
        ) : (
          <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.noMrrData', 'No MRR data yet')}</p>
        )}
      </div>

      <div className="card overflow-hidden">
        <div className="px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
          <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('admin.recentlyOnboarded', 'Recently Onboarded')}</h3>
        </div>
        {(data?.recentRestaurants?.length ?? 0) > 0 ? (
          <table className="w-full">
            <thead>
              <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                {[
                  t('common.restaurant', 'Restaurant'),
                  t('billing.plan', 'Plan'),
                  t('common.status', 'Status'),
                  t('common.joined', 'Joined'),
                  t('common.mrr', 'MRR'),
                ].map(h => (
                  <th key={h} className="text-left px-5 py-3 text-xs font-semibold uppercase tracking-wider" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data!.recentRestaurants.map((r, idx) => (
                <tr key={r.name + idx} className="table-row-hover" style={{ borderBottom: idx < data!.recentRestaurants.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                  <td className="px-5 py-3 font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{r.name}</td>
                  <td className="px-5 py-3"><span className="badge badge-primary">{r.plan}</span></td>
                  <td className="px-5 py-3">
                    <span className={`badge ${r.status === 'active' ? 'badge-success' : r.status === 'trial' ? 'badge-warning' : 'badge-danger'}`}>{r.status}</span>
                  </td>
                  <td className="px-5 py-3 text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{formatTimeSince(r.createdAt, t)}</td>
                  <td className="px-5 py-3 font-semibold tabular-nums text-sm" style={{ color: 'hsl(var(--foreground))' }}>${r.mrr.toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p className="text-sm py-10 text-center" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.noRestaurantsYet', 'No restaurants onboarded yet')}</p>
        )}
      </div>
    </>
  );
}
