'use client';

import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { Plus, ChevronRight, AlertCircle } from 'lucide-react';
import { api } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { cn } from '@/lib/utils';

interface CityStats {
  totals: {
    vihars: number;
    completed: number;
    inProgress: number;
    autoClosed: number;
    totalKm: number;
    activeVolunteers: number;
  };
  pending: { allocations: number; distanceApprovals: number; autoClosed: number };
}

export default function CaptainHome() {
  const { data: me } = useMe();
  const stats = useQuery({
    queryKey: ['stats', 'city', 'this_month'],
    queryFn: () => api.get<CityStats>('/api/stats/city', { query: { period: 'this_month' } }),
  });

  const firstName = me?.fullName?.split(' ')[0] ?? '';

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Greeting */}
      <div>
        <div className="text-xs uppercase tracking-widest text-ink-400">This month</div>
        <div className="font-display text-3xl text-ink mt-1">
          {firstName ? `Jai Jinendra, ${firstName}` : 'Jai Jinendra'}
        </div>
      </div>

      {/* Stat tiles */}
      <div className="grid grid-cols-2 gap-3">
        <StatTile label="Total vihars" value={stats.data?.totals.vihars} accent="ink" />
        <StatTile label="Completed" value={stats.data?.totals.completed} accent="moss" />
        <StatTile
          label="Total km"
          value={stats.data ? stats.data.totals.totalKm.toFixed(1) : undefined}
          accent="saffron"
        />
        <StatTile label="Active sevaks" value={stats.data?.totals.activeVolunteers} accent="ink" />
      </div>

      {/* Attention items */}
      {stats.data && (stats.data.pending.distanceApprovals > 0 || stats.data.pending.autoClosed > 0) && (
        <Card className="border-saffron-300 bg-saffron-50/50">
          <CardHeader className="pb-2">
            <div className="flex items-center gap-2 text-saffron-700">
              <AlertCircle className="w-4 h-4" />
              <CardTitle className="text-base">Needs your attention</CardTitle>
            </div>
          </CardHeader>
          <CardContent className="text-sm text-ink-600 space-y-1.5">
            {stats.data.pending.distanceApprovals > 0 && (
              <div>{stats.data.pending.distanceApprovals} distance approvals pending</div>
            )}
            {stats.data.pending.autoClosed > 0 && (
              <div>{stats.data.pending.autoClosed} auto-closed vihars to review</div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Today's vihars - placeholder list */}
      <section>
        <div className="flex items-baseline justify-between mb-3">
          <h2 className="font-display text-xl text-ink">Today</h2>
          <Link href="/captain/vihars" className="text-xs text-saffron-700 hover:underline">
            View all →
          </Link>
        </div>
        <Card>
          <CardContent className="py-8 text-center text-sm text-ink-400">
            No vihars scheduled for today.
            <br />
            <Link href="/captain/vihars/new" className="text-saffron-700 hover:underline">
              Plan one
            </Link>
          </CardContent>
        </Card>
      </section>

      {/* FAB */}
      <Link href="/captain/vihars/new" className="fixed bottom-20 right-6 z-20">
        <Button size="lg" variant="accent" className="h-14 rounded-full shadow-lg">
          <Plus className="w-5 h-5" />
          New Vihar
        </Button>
      </Link>
    </div>
  );
}

function StatTile({
  label,
  value,
  accent,
}: {
  label: string;
  value: number | string | undefined;
  accent: 'ink' | 'moss' | 'saffron';
}) {
  const accentClass = {
    ink: 'text-ink',
    moss: 'text-moss-700',
    saffron: 'text-saffron-700',
  }[accent];
  return (
    <div className="surface-card p-4">
      <div className="text-[10px] uppercase tracking-widest text-ink-400">{label}</div>
      <div className={cn('font-display text-3xl mt-1 tabular-nums', accentClass)}>
        {value ?? '—'}
      </div>
    </div>
  );
}
