'use client';

import { useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { fmtDate, fmtTime, statusLabel, statusPillClass } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import type { ViharStatusT } from '@vihar/shared';

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

type ViharStatus = ViharStatusT;

interface ViharItem {
  viharId: number;
  viharDate: string;
  plannedStartTime: string;
  headSaintHonorific?: string | null;
  headSaintName: string;
  status: ViharStatus;
  sadhujiCount: number;
  sadhvijiCount: number;
  otherCount: number;
  actualDistanceMeters?: number | null;
  departureLocation: { locationId: number; name: string };
  arrivalLocation: { locationId: number; name: string };
  departureLocality?: { localityId: number; name: string } | null;
  samuday?: { samudayId: number; name: string } | null;
  _count: { allocations: number };
}

interface Locality { localityId: number; name: string }

interface ListResponse { items: ViharItem[]; total: number; page: number; pageSize: number }

// ---- Date helpers ---------------------------------------------------------

type DateRange = 'today' | 'tomorrow' | 'week' | 'month' | 'all';

function toIso(d: Date) { return d.toISOString().slice(0, 10); }

function getDateParams(range: DateRange): { date?: string; dateFrom?: string; dateTo?: string } {
  const now = new Date();
  if (range === 'today') return { date: toIso(now) };
  if (range === 'tomorrow') {
    const d = new Date(now); d.setDate(d.getDate() + 1);
    return { date: toIso(d) };
  }
  if (range === 'week') {
    const from = new Date(now);
    const to = new Date(now); to.setDate(to.getDate() + 6);
    return { dateFrom: toIso(from), dateTo: toIso(to) };
  }
  if (range === 'month') {
    const from = new Date(now.getFullYear(), now.getMonth(), 1);
    const to = new Date(now.getFullYear(), now.getMonth() + 1, 0);
    return { dateFrom: toIso(from), dateTo: toIso(to) };
  }
  return {};
}

// ---- Formatters -----------------------------------------------------------

function fmtDist(meters: number) {
  return `${(meters / 1000).toFixed(1)} km`;
}

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

const STATUS_CHIPS: { label: string; value: ViharStatus | '' }[] = [
  { label: 'All', value: '' },
  { label: 'Planned', value: 'planned' },
  { label: 'In Progress', value: 'in_progress' },
  { label: 'Completed', value: 'completed' },
  { label: 'Cancelled', value: 'cancelled' },
  { label: 'Auto-Closed', value: 'auto_closed' },
];

const DATE_CHIPS: { label: string; value: DateRange }[] = [
  { label: 'Today', value: 'today' },
  { label: 'Tomorrow', value: 'tomorrow' },
  { label: 'This Week', value: 'week' },
  { label: 'This Month', value: 'month' },
  { label: 'All Time', value: 'all' },
];

const PAGE_SIZE = 20;

type AllocationFilter = 'any' | 'unallocated' | 'allocated';

export default function ViharsPage() {
  const router = useRouter();
  const [status, setStatus] = useState<ViharStatus | ''>('');
  const [dateRange, setDateRange] = useState<DateRange>('all');
  const [localityId, setLocalityId] = useState<number | null>(null);
  const [allocFilter, setAllocFilter] = useState<AllocationFilter>('any');
  const [page, setPage] = useState(1);

  const dateParams = useMemo(() => getDateParams(dateRange), [dateRange]);

  const { data, isLoading, isError } = useQuery<ListResponse>({
    queryKey: ['vihars', { status, dateRange, localityId, allocFilter, page }],
    queryFn: () =>
      api.get<ListResponse>('/api/vihars', {
        query: {
          status: status || undefined,
          ...dateParams,
          localityId: localityId ?? undefined,
          allocated: allocFilter === 'any' ? undefined : (allocFilter === 'allocated' ? 'true' : 'false'),
          page,
          pageSize: PAGE_SIZE,
        },
      }),
    placeholderData: (prev) => prev,
  });

  const { data: localities } = useQuery<Locality[]>({
    queryKey: ['localities'],
    queryFn: () => api.get<Locality[]>('/api/localities'),
    staleTime: Infinity,
  });

  function clearFilters() {
    setStatus('');
    setDateRange('all');
    setLocalityId(null);
    setAllocFilter('any');
    setPage(1);
  }

  function handleStatusChip(val: ViharStatus | '') {
    setStatus((prev: ViharStatus | '') => (prev === val ? '' : val));
    setPage(1);
  }

  function handleDateChip(val: DateRange) {
    setDateRange((prev: DateRange) => (prev === val ? 'all' : val));
    setPage(1);
  }

  const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 1;

  return (
    <div className="space-y-4 pb-8">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">All Vihars</h1>
        {data && (
          <p className="mt-0.5 text-sm text-ink-300">{data.total} vihar{data.total !== 1 ? 's' : ''}</p>
        )}
      </div>

      {/* Status chips */}
      <div className="-mx-4 flex flex-nowrap items-center gap-2 overflow-x-auto px-4 pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {STATUS_CHIPS.map(({ label, value }) => (
          <button
            key={value || 'all'}
            onClick={() => handleStatusChip(value)}
            className={`shrink-0 whitespace-nowrap rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              status === value ? 'bg-ink text-paper' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Allocation filter */}
      <div className="-mx-4 flex flex-nowrap items-center gap-2 overflow-x-auto px-4 pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {([
          { label: 'All', value: 'any' as AllocationFilter },
          { label: 'Unallocated', value: 'unallocated' as AllocationFilter },
          { label: 'Allocated', value: 'allocated' as AllocationFilter },
        ]).map(({ label, value }) => (
          <button
            key={value}
            onClick={() => { setAllocFilter(value); setPage(1); }}
            className={`shrink-0 whitespace-nowrap rounded-full px-3 py-1 text-xs font-medium transition-colors ${
              allocFilter === value ? 'bg-moss-700 text-white' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Date + locality row */}
      <div className="-mx-4 flex flex-nowrap items-center gap-2 overflow-x-auto px-4 pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {DATE_CHIPS.map(({ label, value }) => (
          <button
            key={value}
            onClick={() => handleDateChip(value)}
            className={`shrink-0 whitespace-nowrap rounded-full px-3 py-1 text-xs transition-colors ${
              dateRange === value ? 'bg-saffron text-white' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'
            }`}
          >
            {label}
          </button>
        ))}
        {localities && localities.length > 0 && (
          <select
            value={localityId ?? ''}
            onChange={(e) => { setLocalityId(e.target.value ? Number(e.target.value) : null); setPage(1); }}
            className="shrink-0 rounded-full border border-paper-300 bg-white px-3 py-1 text-xs focus:outline-none focus:ring-2 focus:ring-saffron"
          >
            <option value="">All localities</option>
            {localities.map((l) => (
              <option key={l.localityId} value={l.localityId}>{l.name}</option>
            ))}
          </select>
        )}
      </div>

      {/* Loading / error */}
      {isLoading && <p className="py-8 text-center text-sm text-ink-300">Loading…</p>}
      {isError && <p className="py-8 text-center text-sm text-rust">Failed to load vihars.</p>}

      {/* Vihar list */}
      {data && data.items.length === 0 && (
        <Card>
          <CardContent className="py-12 text-center">
            <p className="text-sm text-ink-300">No vihars match your filters.</p>
            <button onClick={clearFilters} className="mt-3 text-sm text-saffron-600 hover:underline">
              Clear filters
            </button>
          </CardContent>
        </Card>
      )}

      {data && data.items.length > 0 && (
        <div className="space-y-2">
          {data.items.map((v) => (
            <button
              key={v.viharId}
              onClick={() => router.push(`/captain/vihars/${v.viharId}`)}
              className="flex w-full flex-col gap-1.5 rounded-lg border border-paper-200 bg-white px-4 py-3 text-left transition-colors hover:bg-paper-50 active:bg-paper-100"
            >
              <div className="flex items-start justify-between gap-2">
                {/* Route */}
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-medium text-ink">
                    {v.departureLocation.name} → {v.arrivalLocation.name}
                  </p>
                  <p className="text-xs text-ink-300">
                    {fmtDate(v.viharDate)} · {fmtTime(v.plannedStartTime)}
                  </p>
                </div>
                {/* Status */}
                <span className={statusPillClass(v.status)}>{statusLabel(v.status)}</span>
              </div>

              {/* Saint name */}
              <p className="text-xs text-ink-400">
                {v.headSaintHonorific ? `${v.headSaintHonorific} ` : ''}{v.headSaintName}
              </p>

              {/* Meta row */}
              <div className="flex flex-wrap items-center gap-2">
                {v.sadhujiCount > 0 && (
                  <span className="rounded bg-paper-100 px-1.5 py-0.5 text-[10px] text-ink-400">
                    {v.sadhujiCount} Sadhuji
                  </span>
                )}
                {v.sadhvijiCount > 0 && (
                  <span className="rounded bg-paper-100 px-1.5 py-0.5 text-[10px] text-ink-400">
                    {v.sadhvijiCount} Sadhviji
                  </span>
                )}
                {v.otherCount > 0 && (
                  <span className="rounded bg-paper-100 px-1.5 py-0.5 text-[10px] text-ink-400">
                    {v.otherCount} Others
                  </span>
                )}
                <span className="text-[10px] text-ink-300">
                  {v._count.allocations} volunteer{v._count.allocations !== 1 ? 's' : ''}
                </span>
                {v.actualDistanceMeters != null && (
                  <span className="text-[10px] text-moss-600">{fmtDist(v.actualDistanceMeters)}</span>
                )}
              </div>
            </button>
          ))}
        </div>
      )}

      {/* Pagination */}
      {data && totalPages > 1 && (
        <div className="flex items-center justify-between pt-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p: number) => Math.max(1, p - 1))}
            disabled={page === 1}
          >
            ← Prev
          </Button>
          <span className="text-sm text-ink-300">Page {page} of {totalPages}</span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p: number) => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
          >
            Next →
          </Button>
        </div>
      )}
    </div>
  );
}
