'use client';

import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { fmtDateLong, fmtTime, fmtTimestamp } from '@/lib/formatters';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import type { ViharStatusT } from '@vihar/shared';

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

type ViharStatus = ViharStatusT;

type DistanceApprovalStatus = 'auto_accepted' | 'pending_captain' | 'approved' | 'rejected';

interface Allocation {
  allocationId: number;
  userId: number;
  isActive: boolean;
  checkInAt?: string | null;
  checkOutAt?: string | null;
  enteredStartTime?: string | null;
  volunteerDistanceKm?: number | null;
  distanceApprovalStatus?: DistanceApprovalStatus | null;
  user: { userId: number; fullName: string };
}

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;
  departureLocation: { locationId: number; name: string; formattedAddress?: string };
  arrivalLocation: { locationId: number; name: string; formattedAddress?: string };
  samuday?: { samudayId: number; name: string } | null;
  allocations: Allocation[];
}

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

function durationLabel(startIso: string, endIso: string) {
  const mins = Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 60000);
  if (mins <= 0) return null;
  const h = Math.floor(mins / 60);
  const m = mins % 60;
  return h > 0 ? `${h}h ${m}m` : `${m}m`;
}

// ---- Status banner --------------------------------------------------------

function Banner({ alloc, viharStatus }: { alloc: Allocation | null | undefined; viharStatus: ViharStatus }) {
  if (viharStatus === 'cancelled') {
    return (
      <div className="rounded-lg bg-paper-200 px-4 py-3 text-center text-sm text-ink-400">
        This vihar was cancelled.
      </div>
    );
  }

  if (!alloc || !alloc.isActive) {
    return (
      <div className="rounded-lg bg-paper-100 px-4 py-3 text-center text-sm text-ink-300">
        You were reassigned. No action needed.
      </div>
    );
  }

  if (!alloc.checkInAt) {
    return (
      <div className="rounded-lg bg-blue-50 border border-blue-200 px-4 py-3 text-center">
        <p className="text-sm font-medium text-blue-700">Upcoming</p>
        <p className="text-xs text-blue-500 mt-0.5">Check in when you arrive at departure</p>
      </div>
    );
  }

  if (!alloc.checkOutAt) {
    return (
      <div className="rounded-lg bg-saffron-50 border border-saffron-200 px-4 py-3 text-center">
        <p className="text-sm font-medium text-saffron-700">In Progress</p>
        <p className="text-xs text-saffron-500 mt-0.5">Checked in at {fmtTimestamp(alloc.checkInAt)}</p>
      </div>
    );
  }

  const dur = durationLabel(alloc.checkInAt, alloc.checkOutAt);
  const approvalStatus = alloc.distanceApprovalStatus;
  return (
    <div className="space-y-2">
      <div className="rounded-lg bg-moss-50 border border-moss-200 px-4 py-3 text-center">
        <p className="text-sm font-medium text-moss-700">Completed</p>
        <p className="text-xs text-moss-600 mt-0.5">
          Walked {alloc.volunteerDistanceKm?.toFixed(1)} km{dur ? ` in ${dur}` : ''}. Thank you 🙏
        </p>
      </div>
      {approvalStatus === 'pending_captain' && (
        <div className="rounded-lg bg-amber-50 border border-amber-200 px-4 py-2 text-center text-xs text-amber-700">
          Distance pending captain approval
        </div>
      )}
      {approvalStatus === 'rejected' && (
        <div className="rounded-lg bg-red-50 border border-red-200 px-4 py-2 text-center text-xs text-rust">
          Distance was adjusted by the captain
        </div>
      )}
    </div>
  );
}

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

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

  const { data: me } = useMe();

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

  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 myAlloc = me
    ? vihar.allocations.find((a) => a.userId === me.userId)
    : undefined;

  const coVolunteers = vihar.allocations
    .filter((a) => a.userId !== me?.userId && a.isActive)
    .map((a) => a.user.fullName.split(' ').slice(0, 2).join(' '));

  const canCheckIn = myAlloc?.isActive && !myAlloc.checkInAt && vihar.status !== 'cancelled';
  const canCheckOut = myAlloc?.isActive && myAlloc.checkInAt && !myAlloc.checkOutAt;
  const isComplete = myAlloc?.isActive && myAlloc.checkInAt && myAlloc.checkOutAt;

  return (
    <div className="space-y-4 pb-36">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Vihar</h1>
        <p className="mt-0.5 text-sm text-ink-300">{fmtDateLong(vihar.viharDate)}</p>
      </div>

      {/* Status banner */}
      <Banner alloc={myAlloc} viharStatus={vihar.status} />

      {/* Vihar info 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="text-sm text-ink-400">{fmtTime(vihar.plannedStartTime)}</div>

          <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>

          <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>
          )}
        </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-center text-sm text-ink-200">↓</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>
        </CardContent>
      </Card>

      {/* Co-volunteers */}
      {coVolunteers.length > 0 && (
        <Card>
          <CardContent className="py-3">
            <p className="text-xs font-medium uppercase tracking-wide text-ink-300 mb-1">Walking with</p>
            <p className="text-sm text-ink">{coVolunteers.join(', ')}</p>
          </CardContent>
        </Card>
      )}

      {/* Sticky action */}
      <div className="fixed bottom-0 left-0 right-0 border-t border-paper-200 bg-paper px-4 py-4 safe-area-inset-bottom">
        <div className="mx-auto max-w-lg space-y-2">
          {canCheckIn && (
            <Button
              className="w-full py-4 text-base"
              onClick={() => router.push(`/volunteer/vihars/${viharId}/check-in`)}
            >
              Check In at Departure
            </Button>
          )}
          {canCheckOut && (
            <Button
              className="w-full py-4 text-base"
              onClick={() => router.push(`/volunteer/vihars/${viharId}/check-out`)}
            >
              Check Out at Arrival
            </Button>
          )}
          {isComplete && (
            <div className="py-2 text-center text-sm text-moss-600 font-medium">
              Walk submitted ✓
            </div>
          )}
          <Button
            variant="ghost"
            className="w-full text-sm"
            onClick={() => router.push('/volunteer')}
          >
            ← Back
          </Button>
        </div>
      </div>
    </div>
  );
}
