'use client';

import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
  Legend, ReferenceLine,
} from 'recharts';
import { SafeChart } from '@client/components/ui/SafeChart';
import { TrendingUp } from 'lucide-react';
import type { HourlyPoint } from '@client/api/analytics';
import { useLanguage } from '@client/contexts/LanguageContext';

const CustomTooltip = ({ active, payload, label, t }: any) => {
  if (active && payload && payload.length) {
    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.color }} />
            <span style={{ color: 'hsl(var(--foreground-secondary))' }}>{t(`dashboard.${entry.name.toLowerCase()}`, entry.name)}:</span>
            <span className="font-semibold tabular-nums font-mono" style={{ color: 'hsl(var(--foreground))' }}>{entry.value}</span>
          </div>
        ))}
      </div>
    );
  }
  return null;
};

function getCurrentHourLabel(): string {
  const h = new Date().getHours();
  const suffix = h >= 12 ? 'PM' : 'AM';
  const display = h > 12 ? h - 12 : h === 0 ? 12 : h;
  return `${display} ${suffix}`;
}

interface HourlyOrderChartProps {
  data: HourlyPoint[];
  loading: boolean;
}

export default function HourlyOrderChart({ data, loading }: HourlyOrderChartProps) {
  const { t } = useLanguage();
  const nowLabel = getCurrentHourLabel();
  const hasData = data.length > 0 && data.some(d => d.orders > 0 || d.reservations > 0);

  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.hourlyActivityToday', 'Hourly Activity — Today')}</p>
          <p className="text-sm font-semibold mt-0.5" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.ordersReservationsByHour', 'Orders & Reservations by Hour')}</p>
        </div>
        <div className="flex items-center gap-1.5 text-xs font-medium" style={{ color: 'hsl(var(--success))' }}>
          <TrendingUp size={14} />
          <span>{t('dashboard.liveData', 'Live data')}</span>
        </div>
      </div>

      {loading ? (
        <div className="h-[220px] flex items-center justify-center">
          <div className="animate-pulse text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('common.loadingChartData', 'Loading chart data...')}</div>
        </div>
      ) : !hasData ? (
        <div className="h-[220px] flex flex-col items-center justify-center text-center">
          <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{t('dashboard.noActivityToday', 'No activity yet today')}</p>
          <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('dashboard.noActivityTodayDesc', 'Orders and reservations will appear here as they come in')}</p>
        </div>
      ) : (
        <SafeChart height={220}>
          <AreaChart data={data} margin={{ top: 4, right: 4, bottom: 0, left: -10 }}>
            <defs>
              <linearGradient id="ordersGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0.25} />
                <stop offset="95%" stopColor="hsl(22, 89%, 48%)" stopOpacity={0.02} />
              </linearGradient>
              <linearGradient id="reservationsGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="hsl(210, 100%, 40%)" stopOpacity={0.2} />
                <stop offset="95%" stopColor="hsl(210, 100%, 40%)" stopOpacity={0.02} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(220, 13%, 91%)" vertical={false} />
            <XAxis dataKey="hour" tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)', fontFamily: 'DM Sans' }} tickLine={false} axisLine={false} interval={2} />
            <YAxis tick={{ fontSize: 11, fill: 'hsl(220, 9%, 46%)', fontFamily: 'DM Sans' }} tickLine={false} axisLine={false} />
            <Tooltip content={<CustomTooltip t={t} />} />
            <ReferenceLine x={nowLabel} stroke="hsl(22, 89%, 48%)" strokeDasharray="4 4" strokeWidth={1.5} label={{ value: t('dashboard.now', 'Now'), fill: 'hsl(22, 89%, 48%)', fontSize: 11 }} />
            <Area type="monotone" dataKey="orders" name={t('dashboard.orders', 'Orders')} stroke="hsl(22, 89%, 48%)" strokeWidth={2} fill="url(#ordersGradient)" dot={false} activeDot={{ r: 4, fill: 'hsl(22, 89%, 48%)', strokeWidth: 0 }} />
            <Area type="monotone" dataKey="reservations" name={t('dashboard.reservations', 'Reservations')} stroke="hsl(210, 100%, 40%)" strokeWidth={2} fill="url(#reservationsGradient)" dot={false} activeDot={{ r: 4, fill: 'hsl(210, 100%, 40%)', strokeWidth: 0 }} />
            <Legend wrapperStyle={{ fontSize: '12px', paddingTop: '12px', fontFamily: 'DM Sans' }} iconType="circle" iconSize={8} />
          </AreaChart>
        </SafeChart>
      )}
    </div>
  );
}
