"use client";

import { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { API_URL } from '@/lib/api';

interface Employee {
  id: number;
  employeeCode: string;
  fullName: string;
  department: string;
  designation: string;
}

interface Attendance {
  id: number;
  employee: Employee;
  attendanceDate: string;
  status: string;
  checkInTime: string;
  checkOutTime: string;
  notes: string;
}

const STATUSES = ["PRESENT", "ABSENT", "HALF_DAY", "LEAVE"];

function todayStr() {
  return new Date().toISOString().slice(0, 10);
}

export default function AttendancePage() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [records, setRecords] = useState<Attendance[]>([]);
  const [date, setDate] = useState(todayStr());
  const [saving, setSaving] = useState<number | null>(null);

  function loadEmployees() {
    fetch(`${API_URL}/api/employees`)
      .then((res) => res.json())
      .then((data) => setEmployees(data))
      .catch((err) => console.error(err));
  }

  function loadAttendance(forDate: string) {
    fetch(`${API_URL}/api/attendance/date/${forDate}`)
      .then((res) => res.json())
      .then((data) => setRecords(data))
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    loadEmployees();
  }, []);

  useEffect(() => {
    loadAttendance(date);
  }, [date]);

  function recordFor(employeeId: number) {
    return records.find((r) => r.employee.id === employeeId);
  }

  async function markStatus(employeeId: number, status: string) {
    setSaving(employeeId);
    try {
      await fetch(`${API_URL}/api/attendance`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ employeeId, attendanceDate: date, status }),
      });
      loadAttendance(date);
    } finally {
      setSaving(null);
    }
  }

  async function checkOut(attendanceId: number) {
    await fetch(`${API_URL}/api/attendance/${attendanceId}/checkout`, {
      method: "PATCH",
    });
    loadAttendance(date);
  }

  const presentCount = records.filter((r) => r.status === "PRESENT").length;
  const absentCount = records.filter((r) => r.status === "ABSENT").length;
  const leaveCount = records.filter((r) => r.status === "LEAVE").length;

  function formatTime(value?: string) {
    if (!value) return "-";
    return new Date(value).toLocaleTimeString("en-GB", {
      hour: "2-digit",
      minute: "2-digit",
    });
  }

  return (
    <DashboardLayout>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">Attendance</h2>
          <p className="mt-1 text-slate-500">
            Daily attendance register for all employees
          </p>
        </div>

        <input
          type="date"
          value={date}
          onChange={(e) => setDate(e.target.value)}
          className="rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        />
      </div>

      <div className="mb-8 grid grid-cols-4 gap-6">
        <StatCard title="Total Employees" value={String(employees.length)} />
        <StatCard title="Present" value={String(presentCount)} />
        <StatCard title="Absent" value={String(absentCount)} />
        <StatCard title="On Leave" value={String(leaveCount)} />
      </div>

      <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white">
        <table className="w-full">
          <thead className="bg-slate-50">
            <tr>
              <th className="px-5 py-4 text-left">Employee</th>
              <th className="px-5 py-4 text-left">Department</th>
              <th className="px-5 py-4 text-left">Status</th>
              <th className="px-5 py-4 text-left">Check In</th>
              <th className="px-5 py-4 text-left">Check Out</th>
              <th className="px-5 py-4 text-left">Mark</th>
            </tr>
          </thead>

          <tbody>
            {employees.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-5 py-16 text-center text-slate-500">
                  No employees found.
                </td>
              </tr>
            ) : (
              employees.map((emp) => {
                const record = recordFor(emp.id);

                return (
                  <tr key={emp.id} className="border-t border-slate-100 hover:bg-slate-50/50">
                    <td className="px-5 py-4">
                      <div className="font-medium text-slate-900">{emp.fullName}</div>
                      <div className="text-xs text-slate-500">{emp.employeeCode}</div>
                    </td>
                    <td className="px-5 py-4">{emp.department || "-"}</td>
                    <td className="px-5 py-4">
                      {record ? (
                        <span
                          className={`rounded-full px-3 py-1 text-xs font-semibold ${
                            record.status === "PRESENT"
                              ? "bg-green-100 text-green-700"
                              : record.status === "ABSENT"
                              ? "bg-red-100 text-red-700"
                              : record.status === "LEAVE"
                              ? "bg-orange-100 text-orange-700"
                              : "bg-slate-100 text-slate-600"
                          }`}
                        >
                          {record.status}
                        </span>
                      ) : (
                        <span className="text-xs text-slate-400">Not marked</span>
                      )}
                    </td>
                    <td className="px-5 py-4 text-sm">{formatTime(record?.checkInTime)}</td>
                    <td className="px-5 py-4 text-sm">
                      {record?.checkOutTime ? (
                        formatTime(record.checkOutTime)
                      ) : record && record.status === "PRESENT" ? (
                        <button
                          onClick={() => checkOut(record.id)}
                          className="text-xs font-semibold text-[#1296E8]"
                        >
                          Check Out
                        </button>
                      ) : (
                        "-"
                      )}
                    </td>
                    <td className="px-5 py-4">
                      <div className="flex gap-2">
                        {STATUSES.map((status) => (
                          <button
                            key={status}
                            disabled={saving === emp.id}
                            onClick={() => markStatus(emp.id, status)}
                            className={`rounded-lg border px-2 py-1 text-xs font-semibold disabled:opacity-50 ${
                              record?.status === status
                                ? "border-[#1296E8] bg-[#1296E8]/10 text-[#1296E8]"
                                : "border-slate-200 text-slate-600 hover:border-[#1296E8]"
                            }`}
                          >
                            {status === "HALF_DAY" ? "HALF" : status.slice(0, 4)}
                          </button>
                        ))}
                      </div>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
    </DashboardLayout>
  );
}

function StatCard({ title, value }: { title: string; value: string }) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <p className="text-sm font-medium text-slate-500">{title}</p>
      <p className="mt-3 text-3xl font-bold text-slate-900">{value}</p>
    </div>
  );
}
