"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { apiClient } from "@/lib/api-client";
import { officeTimezone, zonedDateKey, zonedParts } from "@/lib/timezone";
import type { AttendanceLog, PaginatedResponse } from "@/lib/types";
import { CheckCircleIcon, LocationPinIcon } from "@/components/icons";

const WEEKDAYS = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"];
const MONTHS = [
  "Januari", "Februari", "Maret", "April", "Mei", "Juni",
  "Juli", "Agustus", "September", "Oktober", "November", "Desember",
];

const TOAST_MESSAGES: Record<string, string> = {
  check_in: "Absen berhasil dicatat! Semangat kerja hari ini \u{1F4AA}",
  check_out: "Absen pulang tercatat. Hati-hati di jalan ya! \u{1F64F}",
  offline: "Absen tersimpan di perangkat, akan terkirim otomatis saat koneksi kembali.",
};

function formatDateID(date: Date, timeZone: string): string {
  const { year, month, day, isoWeekday } = zonedParts(date, timeZone);
  return `${WEEKDAYS[isoWeekday % 7]}, ${day} ${MONTHS[month - 1]} ${year}`;
}

function formatClock(date: Date, timeZone: string): string {
  const { hour, minute, second } = zonedParts(date, timeZone);
  return [hour, minute, second]
    .map((n) => String(n).padStart(2, "0"))
    .join(".");
}

function formatHHmm(iso: string, timeZone: string): string {
  const { hour, minute } = zonedParts(new Date(iso), timeZone);
  return `${String(hour).padStart(2, "0")}.${String(minute).padStart(2, "0")}`;
}

function formatDuration(startIso: string, end: Date): string {
  const diffMinutes = Math.max(0, Math.floor((end.getTime() - new Date(startIso).getTime()) / 60000));
  return `${Math.floor(diffMinutes / 60)} jam ${diffMinutes % 60} menit`;
}

function getGreeting(hour: number): { label: string; sub: string; emoji: string } {
  if (hour >= 4 && hour < 11) {
    return { label: "Selamat pagi", sub: "Awali hari dengan semangat!", emoji: "\u{1F324}\u{FE0F}" };
  }
  if (hour >= 11 && hour < 15) {
    return { label: "Selamat siang", sub: "Semangat terus, hari masih panjang!", emoji: "\u{26C5}" };
  }
  if (hour >= 15 && hour < 18) {
    return { label: "Selamat sore", sub: "Sebentar lagi selesai, semangat! Bagi yang baru mulai, selamat bekerja.", emoji: "\u{1F325}\u{FE0F}" };
  }
  return { label: "Selamat malam", sub: "Kerja keras hari ini, jangan lupa istirahat.", emoji: "\u{1F319}" };
}

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

  const [logs, setLogs] = useState<AttendanceLog[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [now, setNow] = useState(() => new Date());
  const [toastMessage, setToastMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!token) return;
    apiClient
      .get<PaginatedResponse<AttendanceLog>>("/attendance/me", token)
      .then((response) => setLogs(response.data))
      .catch(() => setError("Gagal memuat status absensi."))
      .finally(() => setIsLoading(false));
  }, [token]);

  useEffect(() => {
    const timer = setInterval(() => setNow(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const toast = params.get("toast");
    if (!toast || !TOAST_MESSAGES[toast]) return;

    // Reading the redirect's query param requires `window`, so this can only
    // resolve after mount — the standard SSR-safe hydration pattern.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setToastMessage(TOAST_MESSAGES[toast]);
    router.replace("/dashboard", { scroll: false });
    const hideTimer = setTimeout(() => setToastMessage(null), 4500);
    return () => clearTimeout(hideTimer);
    // Reads the URL once on mount to catch the redirect from /absen; router is stable.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // The office's clock, not the device's: schedules and "today" follow the office timezone.
  const timezone = officeTimezone(employee?.office);
  const timeZone = timezone.timeZone;

  const { checkInLog, checkOutLog } = useMemo(() => {
    const todayKey = zonedDateKey(now, timeZone);
    const todayLogs = logs.filter((log) => zonedDateKey(new Date(log.received_at), timeZone) === todayKey);
    return {
      checkInLog: todayLogs.find((log) => log.type === "check_in") ?? null,
      checkOutLog: todayLogs.find((log) => log.type === "check_out") ?? null,
    };
  }, [logs, now, timeZone]);

  const hasCheckedIn = checkInLog != null;
  const hasCheckedOut = checkOutLog != null;
  const isDoneForToday = hasCheckedIn && hasCheckedOut;
  const buttonLabel = hasCheckedIn ? "Absen Pulang" : "Absen Masuk";

  const greeting = getGreeting(zonedParts(now, timeZone).hour);
  const firstName = employee?.name?.split(" ")[0] ?? "Karyawan";
  const seconds = zonedParts(now, timeZone).second;
  const radius = 92;
  const circumference = 2 * Math.PI * radius;
  const progress = seconds / 60;

  const handleActionClick = () => {
    if (isDoneForToday) return;
    router.push("/absen");
  };

  return (
    <div className="space-y-4 pb-2">
      {toastMessage && (
        <div className="fixed inset-x-4 top-4 z-50 mx-auto flex max-w-md items-start gap-2.5 rounded-2xl bg-white px-4 py-3 shadow-lg ring-1 ring-black/5 dark:bg-zinc-800">
          <span className="mt-0.5 flex h-5 w-5 flex-none items-center justify-center rounded-full bg-zinc-900 text-white dark:bg-white dark:text-zinc-900">
            <CheckCircleIcon className="h-3.5 w-3.5" />
          </span>
          <p className="text-sm text-zinc-700 dark:text-zinc-200">{toastMessage}</p>
        </div>
      )}

      <div className="relative overflow-hidden rounded-3xl bg-white p-5 shadow-sm dark:bg-zinc-900">
        <div className="pointer-events-none absolute -right-8 -top-10 h-36 w-36 rounded-full bg-teal-100/70 dark:bg-teal-900/20" />

        <div className="relative space-y-1">
          <p className="text-xs text-zinc-400">{formatDateID(now, timeZone)}</p>
          <h1 className="text-xl font-semibold text-zinc-900 dark:text-zinc-50">
            {greeting.label}, {firstName}! <span>{greeting.emoji}</span>
          </h1>
          <p className="text-sm text-zinc-500">{greeting.sub}</p>
        </div>

        <div className="relative mx-auto mt-6 flex h-56 w-56 items-center justify-center">
          <svg viewBox="0 0 220 220" className="pointer-events-none absolute inset-0 h-full w-full -rotate-90">
            <circle cx="110" cy="110" r={radius} fill="none" strokeWidth="14" className="stroke-zinc-100 dark:stroke-zinc-800" />
            <circle
              cx="110"
              cy="110"
              r={radius}
              fill="none"
              strokeWidth="14"
              strokeLinecap="round"
              className="stroke-teal-500 transition-[stroke-dashoffset] duration-500 ease-linear"
              strokeDasharray={circumference}
              strokeDashoffset={circumference * (1 - progress)}
            />
          </svg>

          <div className="flex flex-col items-center gap-3">
            <p className="text-xs font-medium tracking-widest text-zinc-400">WAKTU SEKARANG</p>
            <p className="font-mono text-3xl font-semibold tabular-nums text-zinc-900 dark:text-zinc-50">
              {formatClock(now, timeZone)}
            </p>
            <p className="-mt-2 text-xs font-medium text-zinc-400">{timezone.label}</p>
            <button
              type="button"
              onClick={handleActionClick}
              disabled={isDoneForToday}
              className={`rounded-full px-6 py-3 text-sm font-semibold transition ${toastMessage ? "ring-2 ring-amber-400 ring-offset-2 ring-offset-white dark:ring-offset-zinc-900" : ""
                } ${isDoneForToday
                  ? "cursor-not-allowed bg-zinc-100 text-zinc-400 dark:bg-zinc-800 dark:text-zinc-600"
                  : hasCheckedIn
                    ? "bg-zinc-100 text-[#0f2a43] dark:bg-zinc-800 dark:text-zinc-100"
                    : "bg-[#0f2a43] text-white"
                }`}
            >
              {buttonLabel}
            </button>
          </div>
        </div>

        <div className="relative mt-6 flex items-start gap-1.5 text-xs text-zinc-500">
          <LocationPinIcon className="h-4 w-4 flex-none text-zinc-400" />
          <p>
            {employee?.office?.name ?? "Kantor belum ditetapkan"}
            {/* — dalam radius kantor{" "} */}
            {/* <span className="text-zinc-400">(validasi geofence: backend)</span> */}
          </p>
        </div>
      </div>

      <div className="rounded-2xl bg-white p-5 shadow-sm dark:bg-zinc-900">
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-50">Status hari ini</h2>
          <span
            className={`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium ${hasCheckedIn
              ? "bg-green-100 text-green-800"
              : "bg-zinc-100 text-zinc-500 dark:bg-zinc-800 dark:text-zinc-400"
              }`}
          >
            {hasCheckedIn ? "✓ Hadir" : "• Belum Absen"}
          </span>
        </div>

        {error && <p className="mt-2 text-xs text-red-600">{error}</p>}
        {isLoading && <p className="mt-2 text-xs text-zinc-400">Memuat...</p>}

        <div className="mt-4 grid grid-cols-3 gap-3 text-center">
          <div className="rounded-xl bg-zinc-50 py-3 dark:bg-zinc-800">
            <p className="text-xs text-zinc-400">Masuk</p>
            <p className="mt-1 text-sm font-semibold text-zinc-900 dark:text-zinc-50">
              {checkInLog ? formatHHmm(checkInLog.received_at, timeZone) : "—"}
            </p>
          </div>
          <div className="rounded-xl bg-zinc-50 py-3 dark:bg-zinc-800">
            <p className="text-xs text-zinc-400">Pulang</p>
            <p className="mt-1 text-sm font-semibold text-zinc-900 dark:text-zinc-50">
              {checkOutLog ? formatHHmm(checkOutLog.received_at, timeZone) : "—"}
            </p>
          </div>
          <div className="rounded-xl bg-zinc-50 py-3 dark:bg-zinc-800">
            <p className="text-xs text-zinc-400">Durasi</p>
            <p className="mt-1 text-sm font-semibold text-zinc-900 dark:text-zinc-50">
              {checkInLog ? formatDuration(checkInLog.received_at, checkOutLog ? new Date(checkOutLog.received_at) : now) : "—"}
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}
