'use client';

import { useState, type ReactNode } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import { fmtDateLong, fmtTime, fmtTimestamp, statusLabel, statusPillClass } from '@/lib/formatters';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import type { ViharStatusT } from '@vihar/shared';

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

type ViharStatus = ViharStatusT;
type ApprovalStatus = 'pending_captain' | 'auto_accepted' | 'approved' | 'rejected';

interface Allocation {
  allocationId: number;
  checkInAt?: string | null;
  checkOutAt?: string | null;
  enteredStartTime?: string | null;
  volunteerDistanceKm?: number | null;
  distanceApprovalStatus?: ApprovalStatus | null;
  enteredByCaptain?: boolean;
  notes?: string | null;
  user: {
    userId: number;
    fullName: string;
    phone: string;
    homeLocality?: { localityId: number; name: string } | null;
  };
}

interface Vihar {
  viharId: number;
  viharDate: string;
  plannedStartTime: string;
  headSaintHonorific?: string | null;
  headSaintName: string;
  sadhujiCount: number;
  sadhvijiCount: number;
  otherCount: number;
  templeDarshan: boolean;
  updhi: boolean;
  remarks?: string | null;
  status: ViharStatus;
  cancelReason?: string | null;
  updatedAt: string;
  departureLocation: { locationId: number; name: string; formattedAddress?: string };
  arrivalLocation: { locationId: number; name: string; formattedAddress?: string };
  samuday?: { samudayId: number; name: string } | null;
  creator?: { userId: number; fullName: string };
  closedBy?: { userId: number; fullName: string } | null;
  allocations: Allocation[];
  plannedDistanceMeters?: number | null;
  actualDistanceKm?: number | null;
}

// ---- Helpers --------------------------------------------------------------

function canReopen(v: Vihar) {
  if (v.status !== 'completed' && v.status !== 'auto_closed') return false;
  return Date.now() - new Date(v.updatedAt).getTime() <= 24 * 60 * 60 * 1000;
}

// ---- Modal wrapper --------------------------------------------------------

function Modal({ title, children, onClose }: { title: string; children: ReactNode; onClose: () => void }) {
  return (
    <div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 sm:items-center">
      <div className="w-full max-w-sm rounded-t-2xl bg-paper px-6 pb-8 pt-6 shadow-xl sm:rounded-xl">
        <h3 className="mb-4 font-display text-lg font-semibold text-ink">{title}</h3>
        {children}
        <button onClick={onClose} className="mt-3 w-full text-sm text-ink-300 hover:text-ink">Cancel</button>
      </div>
    </div>
  );
}

// ---- Allocation row -------------------------------------------------------

function AllocationRow({
  alloc,
  viharStatus,
  onCheckOutOnBehalf,
  onApproveDistance,
  onDeallocate,
}: {
  alloc: Allocation;
  viharStatus: ViharStatus;
  onCheckOutOnBehalf: (a: Allocation) => void;
  onApproveDistance: (a: Allocation) => void;
  onDeallocate: (a: Allocation) => void | Promise<void>;
}) {
  const [menuOpen, setMenuOpen] = useState(false);

  function statusLine() {
    if (!alloc.checkInAt) return <span className="text-xs text-ink-300">Not checked in</span>;
    if (!alloc.checkOutAt) return <span className="text-xs text-saffron-600">Checked in at {fmtTimestamp(alloc.checkInAt)}</span>;
    return (
      <span className="text-xs text-moss-600">
        Checked out · {alloc.volunteerDistanceKm?.toFixed(1)} km
      </span>
    );
  }

  const canCheckOut = alloc.checkInAt && !alloc.checkOutAt && (viharStatus === 'in_progress' || viharStatus === 'planned');
  const canApprove = alloc.distanceApprovalStatus === 'pending_captain';
  const canDealloc = !alloc.checkInAt && (viharStatus === 'planned' || viharStatus === 'in_progress');

  const hasActions = canCheckOut || canApprove || canDealloc;

  return (
    <div className="flex items-start gap-3 py-2.5">
      <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-paper-200 text-xs font-semibold text-ink-400">
        {alloc.user.fullName.split(' ').map((w) => w[0]).join('').slice(0, 2).toUpperCase()}
      </div>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium text-ink">{alloc.user.fullName}</p>
        <div className="flex flex-wrap items-center gap-1.5">
          {alloc.user.homeLocality && (
            <span className="text-xs text-ink-300">{alloc.user.homeLocality.name} ·</span>
          )}
          {statusLine()}
        </div>
        {canApprove && (
          <span className="mt-0.5 inline-block rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-700">
            Distance approval pending
          </span>
        )}
        {alloc.distanceApprovalStatus === 'approved' && (
          <span className="mt-0.5 inline-block rounded bg-moss-100 px-1.5 py-0.5 text-[10px] font-medium text-moss-700">
            Distance approved
          </span>
        )}
      </div>

      {hasActions && (
        <div className="relative">
          <button
            onClick={() => setMenuOpen((v) => !v)}
            className="flex h-7 w-7 items-center justify-center rounded-full text-ink-300 hover:bg-paper-200"
          >
            ⋮
          </button>
          {menuOpen && (
            <div className="absolute right-0 z-10 mt-1 w-48 rounded-lg border border-paper-200 bg-white shadow-lg">
              {canCheckOut && (
                <button
                  onClick={() => { setMenuOpen(false); onCheckOutOnBehalf(alloc); }}
                  className="flex w-full px-3 py-2 text-left text-sm text-ink hover:bg-paper-50"
                >
                  Mark check-out on behalf
                </button>
              )}
              {canApprove && (
                <button
                  onClick={() => { setMenuOpen(false); onApproveDistance(alloc); }}
                  className="flex w-full px-3 py-2 text-left text-sm text-ink hover:bg-paper-50"
                >
                  Approve / reject distance
                </button>
              )}
              {canDealloc && (
                <button
                  onClick={() => { setMenuOpen(false); onDeallocate(alloc); }}
                  className="flex w-full px-3 py-2 text-left text-sm text-rust hover:bg-paper-50"
                >
                  Remove volunteer
                </button>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

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

export default function ViharDetailPage() {
  const { id } = useParams<{ id: string }>();
  const viharId = Number(id);
  const router = useRouter();
  const qc = useQueryClient();

  const { data: vihar, isLoading, isError } = useQuery<Vihar>({
    queryKey: ['vihar', viharId],
    queryFn: () => api.get<Vihar>(`/api/vihars/${viharId}`),
  });

  // Modal states
  const [cancelOpen, setCancelOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelErr, setCancelErr] = useState('');
  const [cancelBusy, setCancelBusy] = useState(false);

  const [closeOpen, setCloseOpen] = useState(false);
  const [closeStart, setCloseStart] = useState('');
  const [closeEnd, setCloseEnd] = useState('');
  const [closeDist, setCloseDist] = useState('');
  const [closeErr, setCloseErr] = useState('');
  const [closeBusy, setCloseBusy] = useState(false);

  const [reopenBusy, setReopenBusy] = useState(false);

  // Checkout on behalf modal
  const [coaAlloc, setCoaAlloc] = useState<Allocation | null>(null);
  const [coaStart, setCoaStart] = useState('');
  const [coaDist, setCoaDist] = useState('');
  const [coaErr, setCoaErr] = useState('');
  const [coaBusy, setCoaBusy] = useState(false);

  // Approve distance modal
  const [adAlloc, setAdAlloc] = useState<Allocation | null>(null);
  const [adKm, setAdKm] = useState('');
  const [adDecision, setAdDecision] = useState<'approved' | 'rejected'>('approved');
  const [adErr, setAdErr] = useState('');
  const [adBusy, setAdBusy] = useState(false);

  function refresh() { qc.invalidateQueries({ queryKey: ['vihar', viharId] }); }

  async function handleCancel() {
    if (!cancelReason.trim()) { setCancelErr('Reason is required'); return; }
    setCancelBusy(true); setCancelErr('');
    try {
      await api.post(`/api/vihars/${viharId}/cancel`, { reason: cancelReason });
      refresh(); setCancelOpen(false);
    } catch (e) {
      setCancelErr(e instanceof ApiError ? e.message : 'Failed');
    } finally { setCancelBusy(false); }
  }

  async function handleClose() {
    if (!closeStart || !closeEnd || !closeDist) { setCloseErr('All fields required'); return; }
    const dist = parseFloat(closeDist);
    if (isNaN(dist) || dist <= 0) { setCloseErr('Invalid distance'); return; }
    if (closeEnd <= closeStart) { setCloseErr('End time must be after start time'); return; }
    setCloseBusy(true); setCloseErr('');
    try {
      await api.post(`/api/vihars/${viharId}/close-manual`, {
        startTime: closeStart,
        endTime: closeEnd,
        distanceKm: dist,
      });
      refresh(); setCloseOpen(false);
    } catch (e) {
      setCloseErr(e instanceof ApiError ? e.message : 'Failed');
    } finally { setCloseBusy(false); }
  }

  async function handleReopen() {
    setReopenBusy(true);
    try {
      await api.post(`/api/vihars/${viharId}/reopen`, {});
      refresh();
    } catch (e) {
      alert(e instanceof ApiError ? e.message : 'Failed to reopen');
    } finally { setReopenBusy(false); }
  }

  function openCoaModal(alloc: Allocation) {
    setCoaAlloc(alloc);
    setCoaStart(vihar?.plannedStartTime.slice(0, 5) ?? '');
    setCoaDist('');
    setCoaErr('');
  }

  async function handleCheckOutOnBehalf() {
    if (!coaAlloc) return;
    const dist = parseFloat(coaDist);
    if (!coaStart || isNaN(dist) || dist <= 0) { setCoaErr('Start time and valid distance required'); return; }
    setCoaBusy(true); setCoaErr('');
    try {
      await api.post(`/api/allocations/${coaAlloc.allocationId}/check-out-on-behalf`, {
        startTime: coaStart,
        distanceKm: dist,
      });
      refresh(); setCoaAlloc(null);
    } catch (e) {
      setCoaErr(e instanceof ApiError ? e.message : 'Failed');
    } finally { setCoaBusy(false); }
  }

  function openAdModal(alloc: Allocation) {
    setAdAlloc(alloc);
    setAdKm(String(alloc.volunteerDistanceKm ?? ''));
    setAdDecision('approved');
    setAdErr('');
  }

  async function handleApproveDistance() {
    if (!adAlloc) return;
    const km = parseFloat(adKm);
    if (isNaN(km) || km <= 0) { setAdErr('Valid distance required'); return; }
    setAdBusy(true); setAdErr('');
    try {
      await api.post(`/api/allocations/${adAlloc.allocationId}/approve-distance`, {
        approvedKm: km,
        decision: adDecision,
      });
      refresh(); setAdAlloc(null);
    } catch (e) {
      setAdErr(e instanceof ApiError ? e.message : 'Failed');
    } finally { setAdBusy(false); }
  }

  async function handleDeallocate(alloc: Allocation) {
    if (!confirm(`Remove ${alloc.user.fullName} from this vihar?`)) return;
    try {
      await api.delete(`/api/allocations/${alloc.allocationId}`);
      refresh();
    } catch (e) {
      alert(e instanceof ApiError ? e.message : 'Failed to remove');
    }
  }

  if (isLoading) return <div className="py-20 text-center text-sm text-ink-300">Loading…</div>;
  if (isError || !vihar) return <div className="py-20 text-center text-sm text-rust">Failed to load vihar.</div>;

  const canModify = vihar.status === 'planned' || vihar.status === 'in_progress';
  const canClose = vihar.status === 'planned' || vihar.status === 'in_progress';
  const canCancel = vihar.status !== 'cancelled' && vihar.status !== 'completed' && vihar.status !== 'auto_closed';

  return (
    <div className="space-y-4 pb-32">
      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="font-display text-2xl font-semibold text-ink">Vihar Detail</h1>
          <p className="mt-0.5 text-sm text-ink-300">{fmtDateLong(vihar.viharDate)}</p>
        </div>
        <span className={statusPillClass(vihar.status)}>{statusLabel(vihar.status)}</span>
      </div>

      {/* Summary card */}
      <Card>
        <CardContent className="space-y-3 pt-4">
          <div>
            <p className="text-lg font-semibold text-ink">
              {vihar.headSaintHonorific ? `${vihar.headSaintHonorific} ` : ''}{vihar.headSaintName}
            </p>
            {vihar.samuday && (
              <p className="text-sm text-ink-300">{vihar.samuday.name}</p>
            )}
          </div>
          <div className="flex items-center gap-1">
            <span className="text-sm text-ink-400">{fmtTime(vihar.plannedStartTime)}</span>
          </div>
          {/* Counts */}
          <div className="flex flex-wrap gap-2">
            {vihar.sadhujiCount > 0 && (
              <span className="rounded bg-paper-100 px-2 py-0.5 text-xs text-ink-500">{vihar.sadhujiCount} Sadhuji</span>
            )}
            {vihar.sadhvijiCount > 0 && (
              <span className="rounded bg-paper-100 px-2 py-0.5 text-xs text-ink-500">{vihar.sadhvijiCount} Sadhviji</span>
            )}
            {vihar.otherCount > 0 && (
              <span className="rounded bg-paper-100 px-2 py-0.5 text-xs text-ink-500">{vihar.otherCount} Others</span>
            )}
          </div>
          {/* Toggles */}
          <div className="flex gap-3 text-xs">
            <span className={vihar.templeDarshan ? 'text-moss-600' : 'text-ink-200'}>
              {vihar.templeDarshan ? '✓' : '–'} Temple Darshan
            </span>
            <span className={vihar.updhi ? 'text-moss-600' : 'text-ink-200'}>
              {vihar.updhi ? '✓' : '–'} Updhi
            </span>
          </div>
          {vihar.remarks && (
            <p className="rounded bg-paper-100 px-3 py-2 text-sm text-ink-400">{vihar.remarks}</p>
          )}
          {vihar.cancelReason && (
            <p className="rounded bg-red-50 px-3 py-2 text-sm text-rust">
              Cancelled: {vihar.cancelReason}
            </p>
          )}
        </CardContent>
      </Card>

      {/* Route card */}
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-base">Route</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          <div>
            <p className="text-xs font-medium uppercase tracking-wide text-ink-300">From</p>
            <p className="text-sm font-medium text-ink">{vihar.departureLocation.name}</p>
            {vihar.departureLocation.formattedAddress && (
              <p className="text-xs text-ink-300">{vihar.departureLocation.formattedAddress}</p>
            )}
          </div>
          <div className="text-ink-200 text-sm text-center">↓</div>
          <div>
            <p className="text-xs font-medium uppercase tracking-wide text-ink-300">To</p>
            <p className="text-sm font-medium text-ink">{vihar.arrivalLocation.name}</p>
            {vihar.arrivalLocation.formattedAddress && (
              <p className="text-xs text-ink-300">{vihar.arrivalLocation.formattedAddress}</p>
            )}
          </div>
          {vihar.actualDistanceKm != null && (
            <div className="flex gap-4 pt-1 text-xs text-ink-400">
              <span>Actual: <strong className="text-ink">{vihar.actualDistanceKm.toFixed(1)} km</strong></span>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Allocations card */}
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-base">Volunteers ({vihar.allocations.length})</CardTitle>
        </CardHeader>
        <CardContent className="pt-0">
          {vihar.allocations.length === 0 && (
            <p className="py-4 text-sm text-ink-300">No volunteers allocated yet.</p>
          )}
          <div className="divide-y divide-paper-100">
            {vihar.allocations.map((alloc) => (
              <AllocationRow
                key={alloc.allocationId}
                alloc={alloc}
                viharStatus={vihar.status}
                onCheckOutOnBehalf={openCoaModal}
                onApproveDistance={openAdModal}
                onDeallocate={handleDeallocate}
              />
            ))}
          </div>
          {canModify && (
            <Button
              variant="outline"
              className="mt-3 w-full"
              onClick={() => router.push(`/captain/vihars/${viharId}/allocate`)}
            >
              + Add more volunteers
            </Button>
          )}
        </CardContent>
      </Card>

      {/* 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 max-w-lg space-y-2">
          <div className="flex gap-2">
            <Button
              variant="outline"
              className="flex-1"
              onClick={() => router.push(`/captain/vihars/${viharId}/share`)}
            >
              Re-share on WhatsApp
            </Button>
            {canReopen(vihar) && (
              <Button
                variant="outline"
                className="flex-1"
                onClick={handleReopen}
                disabled={reopenBusy}
              >
                {reopenBusy ? 'Reopening…' : 'Reopen'}
              </Button>
            )}
          </div>
          <div className="flex gap-2">
            {canClose && (
              <Button
                variant="outline"
                className="flex-1 text-ink-400"
                onClick={() => { setCloseStart(vihar.plannedStartTime.slice(0, 5)); setCloseEnd(''); setCloseDist(''); setCloseErr(''); setCloseOpen(true); }}
              >
                Close Manually
              </Button>
            )}
            {canCancel && (
              <Button
                variant="outline"
                className="flex-1 text-rust border-rust/30 hover:bg-red-50"
                onClick={() => { setCancelReason(''); setCancelErr(''); setCancelOpen(true); }}
              >
                Cancel Vihar
              </Button>
            )}
          </div>
          <Button variant="ghost" className="w-full text-sm" onClick={() => router.push('/captain/vihars')}>
            ← Back to list
          </Button>
        </div>
      </div>

      {/* Cancel modal */}
      {cancelOpen && (
        <Modal title="Cancel Vihar" onClose={() => setCancelOpen(false)}>
          <div className="space-y-3">
            <div>
              <Label className="mb-1 block text-sm">Reason <span className="text-rust">*</span></Label>
              <textarea
                value={cancelReason}
                onChange={(e) => setCancelReason(e.target.value)}
                rows={3}
                placeholder="Briefly explain why…"
                className="w-full rounded-md border border-paper-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-saffron"
              />
            </div>
            {cancelErr && <p className="text-sm text-rust">{cancelErr}</p>}
            <Button
              className="w-full bg-rust text-white hover:bg-rust/90"
              onClick={handleCancel}
              disabled={cancelBusy}
            >
              {cancelBusy ? 'Cancelling…' : 'Confirm Cancel'}
            </Button>
          </div>
        </Modal>
      )}

      {/* Close manually modal */}
      {closeOpen && (
        <Modal title="Close Vihar Manually" onClose={() => setCloseOpen(false)}>
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label className="mb-1 block text-sm">Start time</Label>
                <Input type="time" value={closeStart} onChange={(e) => setCloseStart(e.target.value)} />
              </div>
              <div>
                <Label className="mb-1 block text-sm">End time</Label>
                <Input type="time" value={closeEnd} onChange={(e) => setCloseEnd(e.target.value)} />
              </div>
            </div>
            <div>
              <Label className="mb-1 block text-sm">Distance (km)</Label>
              <Input
                type="number"
                step="0.1"
                min="0"
                value={closeDist}
                onChange={(e) => setCloseDist(e.target.value)}
                placeholder="e.g. 5.2"
              />
            </div>
            {closeErr && <p className="text-sm text-rust">{closeErr}</p>}
            <Button className="w-full" onClick={handleClose} disabled={closeBusy}>
              {closeBusy ? 'Closing…' : 'Close Vihar'}
            </Button>
          </div>
        </Modal>
      )}

      {/* Check-out on behalf modal */}
      {coaAlloc && (
        <Modal title={`Check out — ${coaAlloc.user.fullName}`} onClose={() => setCoaAlloc(null)}>
          <div className="space-y-3">
            <div>
              <Label className="mb-1 block text-sm">Start time</Label>
              <Input type="time" value={coaStart} onChange={(e) => setCoaStart(e.target.value)} />
            </div>
            <div>
              <Label className="mb-1 block text-sm">Distance walked (km)</Label>
              <Input
                type="number"
                step="0.1"
                min="0"
                value={coaDist}
                onChange={(e) => setCoaDist(e.target.value)}
                placeholder="e.g. 5.2"
              />
            </div>
            {coaErr && <p className="text-sm text-rust">{coaErr}</p>}
            <Button className="w-full" onClick={handleCheckOutOnBehalf} disabled={coaBusy}>
              {coaBusy ? 'Saving…' : 'Mark Check-Out'}
            </Button>
          </div>
        </Modal>
      )}

      {/* Approve distance modal */}
      {adAlloc && (
        <Modal title={`Distance — ${adAlloc.user.fullName}`} onClose={() => setAdAlloc(null)}>
          <div className="space-y-3">
            <p className="text-sm text-ink-400">
              Volunteer submitted: <strong className="text-ink">{adAlloc.volunteerDistanceKm?.toFixed(1)} km</strong>
            </p>
            <div>
              <Label className="mb-1 block text-sm">Approved distance (km)</Label>
              <Input
                type="number"
                step="0.1"
                min="0"
                value={adKm}
                onChange={(e) => setAdKm(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setAdDecision('approved')}
                className={`flex-1 rounded-md border py-2 text-sm font-medium transition-colors ${adDecision === 'approved' ? 'border-moss-400 bg-moss-50 text-moss-700' : 'border-paper-300 text-ink-300'}`}
              >
                Approve
              </button>
              <button
                onClick={() => setAdDecision('rejected')}
                className={`flex-1 rounded-md border py-2 text-sm font-medium transition-colors ${adDecision === 'rejected' ? 'border-rust/40 bg-red-50 text-rust' : 'border-paper-300 text-ink-300'}`}
              >
                Reject
              </button>
            </div>
            {adErr && <p className="text-sm text-rust">{adErr}</p>}
            <Button className="w-full" onClick={handleApproveDistance} disabled={adBusy}>
              {adBusy ? 'Saving…' : 'Confirm'}
            </Button>
          </div>
        </Modal>
      )}
    </div>
  );
}
