'use client';

import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { api, ApiError } from '@/lib/api';
import { initials, fmtTime, fmtDate } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

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

interface Vihar {
  viharId: number;
  viharDate: string;
  plannedStartTime: string;
  headSaintHonorific?: string;
  headSaintName: string;
  departureLocation: { name: string };
  arrivalLocation: { name: string };
}

interface Volunteer {
  userId: number;
  fullName: string;
  phone: string;
  homeLocality?: { localityId: number; name: string } | null;
  lifetimeViharCount: number;
  thisMonthViharCount: number;
}

interface Locality { localityId: number; name: string }

type SortKey = 'name' | 'lifetime' | 'month';


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

export default function AllocatePage() {
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const viharId = Number(params.id);

  const [vihar, setVihar] = useState<Vihar | null>(null);
  const [volunteers, setVolunteers] = useState<Volunteer[]>([]);
  const [localities, setLocalities] = useState<Locality[]>([]);
  const [sameDayVihars, setSameDayVihars] = useState<any[]>([]);
  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [search, setSearch] = useState('');
  const [localityFilter, setLocalityFilter] = useState<number | null>(null);
  const [sort, setSort] = useState<SortKey>('name');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  // Load vihar + volunteers + localities in parallel
  useEffect(() => {
    Promise.all([
      api.get<Vihar>(`/api/vihars/${viharId}`),
      api.get<{ items: Volunteer[] }>('/api/users', { query: { role: 'volunteer', isActive: true, pageSize: 200 } }),
      api.get<Locality[]>('/api/localities'),
    ])
      .then(([v, users, locs]) => {
        setVihar(v);
        setVolunteers(users.items);
        setLocalities(locs);
        // Load same-day vihars for conflict detection
        return api.get<{ items: any[] }>('/api/vihars', {
          query: { date: v.viharDate.slice(0, 10), pageSize: 100 },
        });
      })
      .then((res) => setSameDayVihars(res.items))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [viharId]);

  // Build conflict map: volunteerId -> conflicting vihar start time
  const conflictMap = useMemo(() => {
    const map = new Map<number, string>();
    if (!vihar) return map;
    const [vh, vm] = vihar.plannedStartTime.split(':').map(Number);
    const viharMinutes = (vh ?? 0) * 60 + (vm ?? 0);
    for (const v of sameDayVihars) {
      if (v.viharId === viharId) continue;
      const [h, m] = (v.plannedStartTime as string).split(':').map(Number);
      const mins = (h ?? 0) * 60 + (m ?? 0);
      if (Math.abs(mins - viharMinutes) <= 120) {
        for (const alloc of v.allocations ?? []) {
          if (!map.has(alloc.user.userId)) {
            map.set(alloc.user.userId, fmtTime(v.plannedStartTime));
          }
        }
      }
    }
    return map;
  }, [sameDayVihars, vihar, viharId]);

  // Filtered + sorted list
  const filtered = useMemo(() => {
    let list = volunteers.filter((v) => {
      if (localityFilter && v.homeLocality?.localityId !== localityFilter) return false;
      if (search) {
        const q = search.toLowerCase();
        return v.fullName.toLowerCase().includes(q) || v.phone.includes(q);
      }
      return true;
    });
    if (sort === 'name') list = [...list].sort((a, b) => a.fullName.localeCompare(b.fullName));
    if (sort === 'lifetime') list = [...list].sort((a, b) => b.lifetimeViharCount - a.lifetimeViharCount);
    if (sort === 'month') list = [...list].sort((a, b) => a.thisMonthViharCount - b.thisMonthViharCount);
    return list;
  }, [volunteers, localityFilter, search, sort]);

  function toggle(userId: number) {
    setSelected((prev) => {
      const next = new Set(prev);
      next.has(userId) ? next.delete(userId) : next.add(userId);
      return next;
    });
  }

  async function handleSave() {
    if (selected.size === 0) return;
    setSubmitting(true);
    setError('');
    try {
      await api.post(`/api/vihars/${viharId}/allocations`, { userIds: [...selected] });
      router.push(`/captain/vihars/${viharId}/share`);
    } catch (e) {
      setError(e instanceof ApiError ? e.message : 'Failed to save allocations');
      setSubmitting(false);
    }
  }

  if (loading) {
    return <div className="py-20 text-center text-sm text-ink-300">Loading…</div>;
  }

  return (
    <div className="space-y-4 pb-32">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Allocate Volunteers</h1>
      </div>

      {/* Vihar summary banner */}
      {vihar && (
        <Card className="bg-saffron-50 border-saffron-100">
          <CardContent className="py-3 text-sm">
            <p className="font-medium text-ink">
              {vihar.headSaintHonorific ? `${vihar.headSaintHonorific} ` : ''}{vihar.headSaintName}
            </p>
            <p className="text-ink-400">
              {fmtDate(vihar.viharDate)} · {fmtTime(vihar.plannedStartTime)}
            </p>
            <p className="text-ink-400">
              {vihar.departureLocation.name} → {vihar.arrivalLocation.name}
            </p>
          </CardContent>
        </Card>
      )}

      {/* Filters */}
      <div className="flex gap-2">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by name or phone…"
          className="flex-1"
        />
        <select
          value={localityFilter ?? ''}
          onChange={(e) => setLocalityFilter(e.target.value ? Number(e.target.value) : null)}
          className="rounded-md border border-paper-300 bg-white px-2 py-2 text-sm 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>

      {/* Sort */}
      <div className="flex items-center gap-2">
        <span className="text-xs text-ink-300">Sort:</span>
        {([['name', 'Name A–Z'], ['lifetime', 'Most experienced'], ['month', 'Fewest this month']] as [SortKey, string][]).map(([key, label]) => (
          <button
            key={key}
            onClick={() => setSort(key)}
            className={`rounded-full px-3 py-1 text-xs transition-colors ${sort === key ? 'bg-ink text-paper' : 'bg-paper-200 text-ink-400 hover:bg-paper-300'}`}
          >
            {label}
          </button>
        ))}
      </div>

      {/* Volunteer list */}
      <div className="space-y-2">
        {filtered.map((vol) => {
          const isSelected = selected.has(vol.userId);
          const conflict = conflictMap.get(vol.userId);
          return (
            <button
              key={vol.userId}
              onClick={() => toggle(vol.userId)}
              className={`flex w-full items-center gap-3 rounded-lg border px-3 py-3 text-left transition-colors
                ${isSelected ? 'border-saffron-300 bg-saffron-50' : 'border-paper-200 bg-white hover:bg-paper-50'}`}
            >
              {/* Avatar */}
              <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-sm font-semibold
                ${isSelected ? 'bg-saffron text-white' : 'bg-paper-200 text-ink-400'}`}>
                {isSelected ? '✓' : initials(vol.fullName)}
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-ink truncate">{vol.fullName}</p>
                <div className="flex items-center gap-2 flex-wrap">
                  {vol.homeLocality && (
                    <span className="text-xs text-ink-300">{vol.homeLocality.name}</span>
                  )}
                  <span className="text-xs text-ink-200">·</span>
                  <span className="text-xs text-ink-300">{vol.lifetimeViharCount} total</span>
                  <span className="text-xs text-ink-200">·</span>
                  <span className="text-xs text-ink-300">{vol.thisMonthViharCount} this month</span>
                </div>
                {conflict && (
                  <p className="mt-0.5 text-xs text-amber-600">⚠ Already on another vihar at {conflict}</p>
                )}
              </div>
            </button>
          );
        })}

        {filtered.length === 0 && (
          <p className="py-8 text-center text-sm text-ink-300">No volunteers match your filters.</p>
        )}
      </div>

      {error && <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">{error}</p>}

      {/* Sticky footer */}
      <div className="fixed bottom-0 left-0 right-0 border-t border-paper-200 bg-paper px-4 py-3 safe-area-inset-bottom">
        <div className="mx-auto flex max-w-lg items-center gap-3">
          <span className="flex-1 text-sm text-ink-400">
            {selected.size > 0 ? `${selected.size} volunteer${selected.size > 1 ? 's' : ''} selected` : 'None selected'}
          </span>
          <Button
            variant="outline"
            onClick={() => router.push(`/captain/vihars/${viharId}`)}
          >
            ← Back
          </Button>
          <Button
            onClick={handleSave}
            disabled={selected.size === 0 || submitting}
          >
            {submitting ? 'Saving…' : 'Save & Share →'}
          </Button>
        </div>
      </div>
    </div>
  );
}
