'use client';

import { useState, useEffect } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { api, ApiError } from '@/lib/api';
import { useMe } from '@/lib/auth';
import { fmtDate, fmtTime } from '@/lib/formatters';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';

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

interface Allocation {
  allocationId: number;
  userId: number;
  isActive: boolean;
  checkInAt?: string | null;
}

interface Vihar {
  viharId: number;
  viharDate: string;
  plannedStartTime: string;
  headSaintName: string;
  departureLocation: { name: string };
  arrivalLocation: { name: string };
  allocations: Allocation[];
}

interface Coords { lat: number; lng: number; acc: number }

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

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

  const { data: me } = useMe();

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

  const [gpsState, setGpsState] = useState<'idle' | 'loading' | 'ok' | 'denied'>('idle');
  const [coords, setCoords] = useState<Coords | null>(null);
  const [gpsError, setGpsError] = useState('');
  const [withoutGps, setWithoutGps] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');

  // Kick off geolocation automatically on mount
  useEffect(() => {
    if (!navigator.geolocation) {
      setGpsState('denied');
      setGpsError('Geolocation not supported by this browser.');
      return;
    }
    setGpsState('loading');
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setCoords({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude,
          acc: pos.coords.accuracy || 0,
        });
        setGpsState('ok');
      },
      (err) => {
        setGpsError(err.message || 'Location permission denied.');
        setGpsState('denied');
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
    );
  }, []);

  function retryGps() {
    setGpsState('loading');
    setGpsError('');
    setCoords(null);
    setWithoutGps(false);
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        setCoords({ lat: pos.coords.latitude, lng: pos.coords.longitude, acc: pos.coords.accuracy || 0 });
        setGpsState('ok');
      },
      (err) => {
        setGpsError(err.message || 'Location permission denied.');
        setGpsState('denied');
      },
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 },
    );
  }

  const allocationId = me && vihar
    ? vihar.allocations.find((a) => a.userId === me.userId && a.isActive)?.allocationId
    : undefined;

  async function handleSubmit() {
    if (!allocationId) { setSubmitError('Your allocation was not found.'); return; }
    setSubmitting(true);
    setSubmitError('');
    try {
      const body: Record<string, unknown> = { withoutGps };
      if (coords && !withoutGps) {
        body.latitude = coords.lat;
        body.longitude = coords.lng;
        if (coords.acc > 0) body.accuracyMeters = Math.round(coords.acc);
      }
      await api.post(`/api/allocations/${allocationId}/check-in`, body);
      router.push(`/volunteer/vihars/${viharId}`);
    } catch (e) {
      setSubmitError(e instanceof ApiError ? e.message : 'Check-in failed');
      setSubmitting(false);
    }
  }

  const canSubmit = gpsState === 'ok' || withoutGps;

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

  return (
    <div className="space-y-5 pb-32">
      <div>
        <h1 className="font-display text-2xl font-semibold text-ink">Check In</h1>
        <div className="mt-1 h-0.5 w-12 bg-saffron rounded-full" />
      </div>

      {/* Vihar summary */}
      {vihar && (
        <Card className="bg-saffron-50 border-saffron-100">
          <CardContent className="py-3 text-sm">
            <p className="font-medium text-ink">{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>
      )}

      {/* GPS card */}
      <Card>
        <CardContent className="space-y-3 pt-4">
          <p className="text-sm font-medium text-ink">Your location</p>

          {gpsState === 'idle' && (
            <p className="text-sm text-ink-300">Waiting for location…</p>
          )}

          {gpsState === 'loading' && (
            <div className="flex items-center gap-2 text-sm text-saffron-600">
              <svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"/>
              </svg>
              Getting your location…
            </div>
          )}

          {gpsState === 'ok' && coords && (
            <div className="flex items-start gap-3">
              <div className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-moss-100 text-moss-600 text-sm">
                ✓
              </div>
              <div>
                <p className="text-sm font-medium text-moss-700">Location captured</p>
                <p className="text-xs text-ink-300 font-mono">
                  {coords.lat.toFixed(5)}, {coords.lng.toFixed(5)}
                </p>
                {coords.acc > 0 && (
                  <p className="text-xs text-ink-300">Accuracy: ±{Math.round(coords.acc)} m</p>
                )}
              </div>
            </div>
          )}

          {gpsState === 'denied' && (
            <div className="space-y-3">
              <div className="flex items-start gap-2">
                <span className="text-base text-rust">⚠</span>
                <div>
                  <p className="text-sm text-rust">Couldn't get location</p>
                  <p className="text-xs text-ink-300 mt-0.5">{gpsError}</p>
                </div>
              </div>
              <button
                onClick={retryGps}
                className="text-sm text-saffron-600 hover:underline"
              >
                Try again
              </button>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={withoutGps}
                  onChange={(e) => setWithoutGps(e.target.checked)}
                  className="h-4 w-4 rounded border-paper-300 accent-saffron"
                />
                <span className="text-sm text-ink-400">Continue without GPS</span>
              </label>
            </div>
          )}
        </CardContent>
      </Card>

      {!allocationId && !isLoading && (
        <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">
          Your allocation was not found for this vihar.
        </p>
      )}

      {submitError && (
        <p className="rounded-md bg-red-50 px-3 py-2 text-sm text-rust">{submitError}</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 flex-col gap-2">
          <Button
            className="w-full py-4 text-base"
            onClick={handleSubmit}
            disabled={!canSubmit || submitting || !allocationId}
          >
            {submitting ? 'Checking in…' : 'Confirm Check-In'}
          </Button>
          <Button variant="ghost" className="w-full text-sm" onClick={() => router.back()}>
            Cancel
          </Button>
        </div>
      </div>
    </div>
  );
}
