"use client";

import { useEffect, useState } from "react";
import { useAuth } from "@/lib/auth-context";
import { apiClient } from "@/lib/api-client";
import { officeTimezone, type OfficeTimezone } from "@/lib/timezone";
import type { AttendanceLog, PaginatedResponse } from "@/lib/types";
import { AttendanceStatusBadge } from "@/components/attendance-status-badge";

/** The log's time in the timezone of the office it was recorded at. */
function formatLogTime(log: AttendanceLog, timezone: OfficeTimezone): string {
  return `${new Date(log.received_at).toLocaleString("id-ID", { timeZone: timezone.timeZone })} ${timezone.label}`;
}

export default function RiwayatPage() {
  const { token, employee } = useAuth();
  const [logs, setLogs] = useState<AttendanceLog[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  return (
    <div className="space-y-4">
      <h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-50">Riwayat Absensi</h1>

      {isLoading && <p className="text-sm text-zinc-500">Memuat...</p>}
      {error && <p className="text-sm text-red-600">{error}</p>}
      {!isLoading && !error && logs.length === 0 && (
        <p className="text-sm text-zinc-400">Belum ada riwayat.</p>
      )}

      <ul className="space-y-3">
        {logs.map((log) => (
          <li key={log.id} className="rounded-xl bg-white p-4 shadow-sm dark:bg-zinc-900">
            <div className="flex items-center justify-between">
              <p className="font-medium text-zinc-900 dark:text-zinc-50">
                {log.type === "check_in" ? "Absen Masuk" : "Absen Keluar"}
              </p>
              <AttendanceStatusBadge status={log.review_status} />
            </div>
            <p className="text-sm text-zinc-500">{formatLogTime(log, officeTimezone(log.office ?? employee?.office))}</p>
            {log.distance_from_office_meters != null && (
              <p className="text-xs text-zinc-400">
                Jarak dari kantor: {Math.round(log.distance_from_office_meters)} m
              </p>
            )}
            {log.flag_reasons && log.flag_reasons.length > 0 && (
              <p className="mt-1 text-xs text-amber-600">Ditandai: {log.flag_reasons.join(", ")}</p>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}
