"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { apiClient, ApiError, isNetworkError } from "@/lib/api-client";
import { buildAttendanceFormData, enqueueAttendance, flushPendingAttendance } from "@/lib/offline-queue";
import { LocationError, useGeolocation } from "@/hooks/use-geolocation";
import { CameraCapture } from "@/components/camera-capture";
import { LocationHelp } from "@/components/location-help";
import { WatermarkCanvas } from "@/components/watermark-canvas";
import { officeTimezone, zonedParts, zonedTimeOnSameDay } from "@/lib/timezone";
import type { AttendanceLog, AttendanceType, Division, PaginatedResponse } from "@/lib/types";

type Step = "loading" | "capture" | "preview" | "submitting";

/**
 * The earliest moment, on `now`'s calendar day in `timeZone`, the given
 * division allows a check-in: check_in_allowed_before_mins minutes before
 * start_hour (read as office-local time, matching the backend).
 */
function earliestCheckInAt(startHour: string, allowedBeforeMins: number, now: Date, timeZone: string): Date {
  const [hours, minutes] = startHour.split(":").map(Number);
  const scheduled = zonedTimeOnSameDay(now, hours, minutes, timeZone);
  return new Date(scheduled.getTime() - allowedBeforeMins * 60_000);
}

/** The division's start_hour on `now`'s weekday in `timeZone`, honouring any per-day override (e.g. a shorter Saturday). */
function startHourOn(division: Division, now: Date, timeZone: string): string {
  const { isoWeekday } = zonedParts(now, timeZone);
  return division.day_schedules?.find((schedule) => schedule.weekday === isoWeekday)?.start_hour ?? division.start_hour;
}

function formatTime(date: Date, timeZone: string): string {
  return date.toLocaleTimeString("id-ID", { hour: "2-digit", minute: "2-digit", timeZone });
}

export default function AbsenPage() {
  const { token, employee } = useAuth();
  const router = useRouter();
  const geolocation = useGeolocation();

  const [step, setStep] = useState<Step>("loading");
  const [nextType, setNextType] = useState<AttendanceType>("check_in");
  const [photo, setPhoto] = useState<Blob | null>(null);
  const [capturedAt, setCapturedAt] = useState<Date | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    const interval = setInterval(() => setNow(new Date()), 15_000);
    return () => clearInterval(interval);
  }, []);

  const division = employee?.division;
  const timezone = useMemo(() => officeTimezone(employee?.office), [employee?.office]);
  const checkInOpensAt =
    nextType === "check_in" && division
      ? earliestCheckInAt(startHourOn(division, now, timezone.timeZone), division.check_in_allowed_before_mins, now, timezone.timeZone)
      : null;
  const isCheckInTooEarly = checkInOpensAt !== null && now < checkInOpensAt;

  useEffect(() => {
    if (!token) return;
    apiClient
      .get<PaginatedResponse<AttendanceLog>>("/attendance/me", token)
      .then((response) => setNextType(response.data[0]?.type === "check_in" ? "check_out" : "check_in"))
      .catch(() => setError("Gagal memuat status absensi terakhir."))
      .finally(() => setStep("capture"));
  }, [token]);

  useEffect(() => {
    if (!token) return;
    const flush = () => flushPendingAttendance(token);
    flush();
    window.addEventListener("online", flush);
    return () => window.removeEventListener("online", flush);
  }, [token]);

  const handleCapture = useCallback(
    async (blob: Blob) => {
      setError(null);
      try {
        await geolocation.refresh();
        setPhoto(blob);
        setCapturedAt(new Date());
        setStep("preview");
      } catch (err) {
        // Location failures get their own guided panel instead of the generic banner.
        if (!(err instanceof LocationError)) {
          setError(err instanceof Error ? err.message : "Gagal mendapatkan lokasi.");
        }
      }
    },
    [geolocation],
  );

  // Surface a permission that is already blocked as soon as the page opens,
  // before the employee bothers taking a photo.
  const locationIssue = geolocation.errorCode ?? (geolocation.permission === "denied" ? "denied" : null);
  const retryLocation = () => {
    geolocation.refresh().catch(() => {
      // The hook keeps the failure in state; LocationHelp re-renders with it.
    });
  };

  const handleRetake = () => {
    setPhoto(null);
    setCapturedAt(null);
    setStep("capture");
  };

  const handleSubmit = async () => {
    if (!token || !photo || !capturedAt || !geolocation.reading) return;
    setStep("submitting");
    setError(null);

    const entry = {
      photo,
      latitude: geolocation.reading.latitude,
      longitude: geolocation.reading.longitude,
      accuracy_meters: geolocation.reading.accuracy,
      mock_detected: false,
      client_timestamp: capturedAt.toISOString(),
    };

    try {
      const formData = buildAttendanceFormData(entry);
      const endpoint = nextType === "check_in" ? "check-in" : "check-out";
      await apiClient.postForm<{ data: AttendanceLog }>(`/attendance/${endpoint}`, formData, token);
      router.replace(`/dashboard?toast=${nextType}`);
    } catch (err) {
      if (isNetworkError(err)) {
        await enqueueAttendance({ endpoint: nextType, ...entry });
        router.replace("/dashboard?toast=offline");
        return;
      }
      setError(err instanceof ApiError ? err.message : "Gagal mengirim absensi.");
      setStep("preview");
    }
  };

  if (step === "loading") {
    return <p className="text-sm text-zinc-500">Memuat...</p>;
  }

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-50">
          {nextType === "check_in" ? "Absen Masuk" : "Absen Pulang"}
        </h1>
        {/* <p className="text-sm text-zinc-500">
          Sesi ini berjalan di browser, bukan aplikasi terverifikasi — deteksi lokasi palsu
          bergantung sepenuhnya pada pemeriksaan di server.
        </p> */}
      </div>

      {error && (
        <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950 dark:text-red-300">
          {error}
        </p>
      )}

      {step === "capture" && isCheckInTooEarly && checkInOpensAt && (
        <p className="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800 dark:bg-amber-950 dark:text-amber-200">
          Absen masuk baru bisa dilakukan mulai pukul {formatTime(checkInOpensAt, timezone.timeZone)} {timezone.label}.
        </p>
      )}

      {step === "capture" && locationIssue && (
        <LocationHelp code={locationIssue} onRetry={retryLocation} retrying={geolocation.status === "loading"} />
      )}

      {step === "capture" && !isCheckInTooEarly && (
        <CameraCapture onCapture={handleCapture} disabled={geolocation.status === "loading"} />
      )}

      {step === "preview" && photo && capturedAt && geolocation.reading && (
        <div className="flex flex-col items-center gap-3">
          <WatermarkCanvas
            photo={photo}
            latitude={geolocation.reading.latitude}
            longitude={geolocation.reading.longitude}
            capturedAt={capturedAt}
            timezone={timezone}
            className="w-full max-w-sm rounded-xl"
          />
          <p className="text-xs text-zinc-500">Akurasi GPS: ±{Math.round(geolocation.reading.accuracy)} m</p>
          <div className="flex w-full max-w-sm gap-3">
            <button
              type="button"
              onClick={handleRetake}
              className="flex-1 rounded-full border border-zinc-300 px-4 py-2.5 text-sm font-medium dark:border-zinc-700"
            >
              Ambil Ulang
            </button>
            <button
              type="button"
              onClick={handleSubmit}
              className="flex-1 rounded-full bg-[#0f2a43] px-4 py-2.5 text-sm font-medium text-white"
            >
              Kirim
            </button>
          </div>
        </div>
      )}

      {step === "submitting" && <p className="text-sm text-zinc-500">Mengirim...</p>}
    </div>
  );
}
