'use client';

import { useState, useRef } from 'react';
import { getAnalyticsDashboard, type DashboardResponse, type DashboardPeriod } from '@client/api/analytics';
import { listConversations, type Conversation } from '@client/api/conversations';
import { listLowStockItems, type LowStockItem } from '@client/api/menu';
import { usePolling } from '@client/hooks/usePolling';
import KPIBentoGrid from './components/KPIBentoGrid';
import HourlyOrderChart from './components/HourlyOrderChart';
import ChannelBreakdownChart from './components/ChannelBreakdownChart';
import ActiveConversationsFeed from './components/ActiveConversationsFeed';
import EscalationAlerts from './components/EscalationAlerts';
import AgentStatusPanel from './components/AgentStatusPanel';
import LowStockAlerts from './components/LowStockAlerts';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

export default function RestaurantDashboardPage() {
  const { t, currentLang } = useLanguage();
  const today = new Date()?.toLocaleDateString(currentLang || 'en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
  usePageHeader(t('nav.agentOverview', 'Agent Overview'), today);

  const PERIODS: { id: DashboardPeriod; label: string }[] = [
    { id: 'today', label: t('period.today', 'Today') },
    { id: '7days', label: t('period.7days', '7 Days') },
    { id: 'month', label: t('period.thisMonth', 'This Month') },
    { id: 'lifetime', label: t('period.allTime', 'All Time') },
  ];

  const [dashboard, setDashboard] = useState<DashboardResponse | null>(null);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [escalations, setEscalations] = useState<Conversation[]>([]);
  const [lowStock, setLowStock] = useState<LowStockItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState<DashboardPeriod>('today');
  const periodRef = useRef<DashboardPeriod>('today');

  const fetchLowStock = async () => {
    try {
      const res = await listLowStockItems();
      setLowStock(res.items ?? []);
    } catch {
      // surface stays as previous snapshot; polling will retry
    }
  };

  const fetchData = async () => {
    try {
      const currentPeriod = periodRef.current;
      const [dashRes, convRes, escRes, lowRes] = await Promise.all([
        getAnalyticsDashboard({ period: currentPeriod }),
        listConversations({ limit: '10', sort_field: 'created_at', sort_dir: 'desc' }),
        listConversations({ status: 'human', limit: '20', sort_field: 'created_at', sort_dir: 'desc' }),
        listLowStockItems().catch(() => ({ items: [] as LowStockItem[] })),
      ]);
      setDashboard(dashRes);
      setConversations(convRes.conversations ?? []);
      setEscalations(escRes.conversations ?? []);
      setLowStock(lowRes.items ?? []);
    } catch {
    } finally {
      setLoading(false);
    }
  };

  usePolling(fetchData, { intervalMs: 5000, runOnMount: true });

  const handlePeriodChange = (newPeriod: DashboardPeriod) => {
    if (newPeriod === periodRef.current) return;
    periodRef.current = newPeriod;
    setPeriod(newPeriod);
    setLoading(true);
    fetchData();
  };

  return (
    <>
      <div className="space-y-6">
        <div className="flex items-center justify-end">
          <div className="flex items-center gap-1 p-1 rounded-lg" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            {PERIODS.map((p) => (
              <button
                key={p.id}
                onClick={() => handlePeriodChange(p.id)}
                className="px-3 py-1.5 rounded-md text-xs font-semibold transition-all"
                style={
                  period === p.id
                    ? { backgroundColor: 'hsl(var(--primary))', color: '#fff' }
                    : { backgroundColor: 'transparent', color: 'hsl(var(--muted-foreground))' }
                }
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>

        <KPIBentoGrid stats={dashboard?.stats ?? null} loading={loading} period={period} />

        <div className="grid grid-cols-1 lg:grid-cols-5 xl:grid-cols-5 2xl:grid-cols-5 gap-4">
          <div className="col-span-1 lg:col-span-3 xl:col-span-3 2xl:col-span-3">
            <HourlyOrderChart data={dashboard?.hourly ?? []} loading={loading} />
          </div>
          <div className="col-span-1 lg:col-span-2 xl:col-span-2 2xl:col-span-2">
            <ChannelBreakdownChart data={dashboard?.channels ?? []} loading={loading} period={period} />
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-12 xl:grid-cols-12 2xl:grid-cols-12 gap-4">
          <div className="col-span-1 lg:col-span-3 xl:col-span-3 2xl:col-span-3">
            <EscalationAlerts escalations={escalations} loading={loading} />
          </div>
          <div className="col-span-1 lg:col-span-6 xl:col-span-6 2xl:col-span-6">
            <ActiveConversationsFeed conversations={conversations} loading={loading} />
          </div>
          <div className="col-span-1 lg:col-span-3 xl:col-span-3 2xl:col-span-3">
            <AgentStatusPanel stats={dashboard?.stats ?? null} loading={loading} />
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4">
          <LowStockAlerts items={lowStock} loading={loading} onRestocked={fetchLowStock} />
        </div>
      </div>
    </>
  );
}
