'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { DailyTrendChart, ByLocalityChart, BySamudayChart, TopContributorsChart } from '@/components/charts/chart-suite';

// ---- Types ----------------------------------------------------------------

type Period = 'today' | 'this_week' | 'this_month' | 'this_year' | 'custom';

interface CityStats {
  period: { from: string; to: string };
  totals: {
    vihars: number; completed: number; totalKm: number; activeVolunteers: number;
  };
  pending: { allocations: number; distanceApprovals: number };
  topContributors: Array<{ userId: number; fullName: string; viharCount: number; totalKm: number }>;
  vihrsByLocality: Array<{ localityId: number | null; name: string; count: number }>;
  vihrsBySamuday: Array<{ samudayId: number | null; name: string; count: number }>;
  dailyTrend: Array<{ date: string; count: number }>;
}

// ---- Tile -----------------------------------------------------------------

function Tile({ label, value, sub }: { label: string; value: string | number; sub?: string }) {
  return (
    <div className="flex flex-col rounded-lg border border-paper-200 bg-white p-3">
      <span className="text-xs font-medium uppercase tracking-wide text-ink-300">{label}</span>
      <span className="mt-1 text-2xl font-semibold tabular-nums text-ink">{value}</span>
      {sub && <span className="text-xs text-ink-300">{sub}</span>}
    </div>
  );
}

// ---- Page -----------------------------------------------------------------

const PERIOD_CHIPS: { label: string; value: Period }[] = [
  { label: 'Today', value: 'today' },
  { label: 'This Week', value: 'this_week' },
  { label: 'This Month', value: 'this_month' },
  { label: 'This Year', value: 'this_year' },
  { label: 'Custom', value: 'custom' },
];

export default function CaptainStatsPage() {
  const [period, setPeriod] = useState<Period>('this_month');
  const [customFrom, setCustomFrom] = useState('');
  const [customTo, setCustomTo] = useState('');

  const customRangeValid = period !== 'custom' || (!!customFrom && !!customTo && customFrom <= customTo);

  const query: Record<string, string | number> = { period };
  if (period === 'custom' && customFrom && customTo) {
    query.from = customFrom;
    query.to = customTo;
  }

  const { data, isLoading } = useQuery<CityStats>({
    queryKey: ['cityStats', query],
    queryFn: () => api.get<CityStats>('/api/stats/city', { query }),
    enabled: customRangeValid,
    staleTime: 60 * 1000,
  });

  return (
    <div className="space-y-5 pb-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Statistics</h1>
        {data && (
          <p className="mt-0.5 text-xs text-ink-300">
            {new Date(data.period.from).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' })}
            {' – '}
            {new Date(data.period.to).toLocaleDateString('en-IN', { day: 'numeric', month: 'short' })}
          </p>
        )}
      </div>

      {/* Period chips */}
      <div className="flex flex-wrap gap-2">
        {PERIOD_CHIPS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => setPeriod(value)}
            className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              period === value ? 'bg-ink text-paper' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {period === 'custom' && (
        <div className="flex gap-2">
          <div className="flex-1">
            <label className="mb-1 block text-xs text-ink-300">From</label>
            <Input type="date" value={customFrom} onChange={(e) => setCustomFrom(e.target.value)} />
          </div>
          <div className="flex-1">
            <label className="mb-1 block text-xs text-ink-300">To</label>
            <Input type="date" value={customTo} onChange={(e) => setCustomTo(e.target.value)} />
          </div>
        </div>
      )}

      {period === 'custom' && customFrom && customTo && customFrom > customTo && (
        <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">"From" date must be before "To" date.</p>
      )}

      {isLoading && <p className="py-8 text-center text-sm text-ink-300">Loading…</p>}

      {data && (
        <>
          {/* Big number tiles */}
          <div className="grid grid-cols-2 gap-3">
            <Tile label="Total vihars" value={data.totals.vihars} />
            <Tile label="Completed" value={data.totals.completed} />
            <Tile label="Total km" value={data.totals.totalKm.toFixed(1)} />
            <Tile label="Active sevaks" value={data.totals.activeVolunteers} />
          </div>

          {/* Pending */}
          {(data.pending.allocations > 0 || data.pending.distanceApprovals > 0) && (
            <Card className="border-amber-200 bg-amber-50">
              <CardContent className="py-3 text-sm">
                {data.pending.allocations > 0 && (
                  <p className="text-amber-700">⚠ {data.pending.allocations} upcoming vihar{data.pending.allocations !== 1 ? 's' : ''} without volunteers</p>
                )}
                {data.pending.distanceApprovals > 0 && (
                  <p className="text-amber-700">⚠ {data.pending.distanceApprovals} distance approval{data.pending.distanceApprovals !== 1 ? 's' : ''} pending</p>
                )}
              </CardContent>
            </Card>
          )}

          {/* Daily trend */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-base">Daily trend (last 30 days)</CardTitle>
            </CardHeader>
            <CardContent>
              <DailyTrendChart data={data.dailyTrend} />
            </CardContent>
          </Card>

          {/* By locality */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-base">Vihars by locality</CardTitle>
            </CardHeader>
            <CardContent>
              <ByLocalityChart data={data.vihrsByLocality} />
            </CardContent>
          </Card>

          {/* By samuday */}
          {data.vihrsBySamuday.length > 0 && (
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-base">Vihars by samuday</CardTitle>
              </CardHeader>
              <CardContent>
                <BySamudayChart data={data.vihrsBySamuday} />
              </CardContent>
            </Card>
          )}

          {/* Top contributors */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-base">Top contributors</CardTitle>
            </CardHeader>
            <CardContent>
              <TopContributorsChart data={data.topContributors} />
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
