"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { API_URL } from '@/lib/api';

interface Employee {
  id: number;
  employeeCode: string;
  fullName: string;
  department: string;
  designation: string;
  phone: string;
  email: string;
  joiningDate: string;
  employmentStatus: string;
  reportingManager: string;
  trainingStatus: string;
  notes: string;
  createdAt: string;
  updatedAt: string;
}

interface ServiceCall {
  id: number;
  serviceCallCode: string;
  issueTitle: string;
  priority: string;
  status: string;
  scheduledDate: string;
  customer: { clinicName: string };
  machine: { manufacturer: string; model: string };
}

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

export default function EmployeeProfilePage() {
  const params = useParams();
  const id = params.id;

  const [employee, setEmployee] = useState<Employee | null>(null);
  const [serviceCalls, setServiceCalls] = useState<ServiceCall[]>([]);
  const [attendance, setAttendance] = useState<Attendance[]>([]);
  const [statusFilter, setStatusFilter] = useState("ALL");

  useEffect(() => {
    fetch(`${API_URL}/api/employees/${id}`)
      .then((res) => res.json())
      .then((data) => setEmployee(data))
      .catch((err) => console.error(err));

    fetch(`${API_URL}/api/service-calls/engineer/${id}`)
      .then((res) => res.json())
      .then((data) => setServiceCalls(data))
      .catch((err) => console.error(err));

    fetch(`${API_URL}/api/attendance/employee/${id}`)
      .then((res) => res.json())
      .then((data) => setAttendance(data))
      .catch((err) => console.error(err));
  }, [id]);

  if (!employee) {
    return (
      <DashboardLayout>
        <p className="text-slate-500">Loading employee profile...</p>
      </DashboardLayout>
    );
  }

  const initials = employee.fullName
    .split(" ")
    .map((name) => name[0])
    .join("")
    .substring(0, 2)
    .toUpperCase();

  return (
    <DashboardLayout>
      <div className="mb-6 text-sm text-slate-500">
        Employees /{" "}
        <span className="font-semibold text-[#1296E8]">
          {employee.employeeCode}
        </span>
      </div>

      <div className="mb-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-6">
            <div className="flex h-20 w-20 items-center justify-center rounded-full bg-[#1296E8]/10 text-3xl font-bold text-[#1296E8]">
              {initials}
            </div>

            <div>
              <p className="text-sm font-semibold text-[#1296E8]">
                {employee.employeeCode}
              </p>

              <h1 className="mt-1 text-4xl font-bold text-slate-900">
                {employee.fullName}
              </h1>

              <p className="mt-2 text-slate-500">
                {employee.designation} • {employee.department}
              </p>

              <p className="mt-1 text-sm text-slate-400">
                Joined {employee.joiningDate || "-"}
              </p>
            </div>
          </div>

          <span className="rounded-full bg-green-100 px-4 py-2 text-sm font-semibold text-green-700">
            {employee.employmentStatus}
          </span>
        </div>

        <div className="mt-8 flex gap-3">
          {["Edit Profile", "Documents", "Leave", "Tasks", "Activity"].map(
            (action) => (
              <button
                key={action}
                className="rounded-xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50"
              >
                {action}
              </button>
            )
          )}
        </div>
      </div>

      <div className="grid grid-cols-3 gap-6">
        <Card title="Contact Details">
          <Info label="Phone" value={employee.phone} />
          <Info label="Email" value={employee.email} />
        </Card>

        <Card title="Employment Details">
          <Info label="Department" value={employee.department} />
          <Info label="Designation" value={employee.designation} />
          <Info label="Joining Date" value={employee.joiningDate} />
          <Info label="Reporting Manager" value={employee.reportingManager} />
        </Card>

        <Card title="Training">
          <Info label="Training Status" value={employee.trainingStatus} />
        </Card>
      </div>

      <div className="mt-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="mb-5 flex items-center justify-between">
          <h3 className="text-lg font-bold">Assigned Service Calls</h3>

          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="rounded-xl border border-slate-200 px-4 py-2 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
          >
            {["ALL", "OPEN", "IN_PROGRESS", "COMPLETED", "CLOSED"].map(
              (status) => (
                <option key={status} value={status}>
                  {status === "ALL" ? "All Statuses" : status}
                </option>
              )
            )}
          </select>
        </div>

        <div className="overflow-hidden rounded-xl border border-slate-200">
          <table className="w-full">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left text-sm">Code</th>
                <th className="px-4 py-3 text-left text-sm">Issue</th>
                <th className="px-4 py-3 text-left text-sm">Customer</th>
                <th className="px-4 py-3 text-left text-sm">Priority</th>
                <th className="px-4 py-3 text-left text-sm">Status</th>
                <th className="px-4 py-3 text-left text-sm">Scheduled</th>
              </tr>
            </thead>

            <tbody>
              {serviceCalls
                .filter(
                  (call) =>
                    statusFilter === "ALL" || call.status === statusFilter
                )
                .map((call) => (
                  <tr
                    key={call.id}
                    className="border-t border-slate-100 hover:bg-slate-50/50"
                  >
                    <td className="px-4 py-3">
                      <Link
                        href={`/service-calls/${call.id}`}
                        className="font-semibold text-[#1296E8]"
                      >
                        {call.serviceCallCode}
                      </Link>
                    </td>
                    <td className="px-4 py-3 text-sm">{call.issueTitle}</td>
                    <td className="px-4 py-3 text-sm">
                      {call.customer?.clinicName || "-"}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-semibold ${
                          call.priority === "CRITICAL"
                            ? "bg-red-100 text-red-700"
                            : call.priority === "HIGH"
                            ? "bg-orange-100 text-orange-700"
                            : call.priority === "LOW"
                            ? "bg-slate-100 text-slate-600"
                            : "bg-blue-100 text-blue-700"
                        }`}
                      >
                        {call.priority}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-semibold ${
                          call.status === "OPEN"
                            ? "bg-yellow-100 text-yellow-700"
                            : call.status === "IN_PROGRESS"
                            ? "bg-blue-100 text-blue-700"
                            : call.status === "CLOSED"
                            ? "bg-green-100 text-green-700"
                            : "bg-slate-100 text-slate-600"
                        }`}
                      >
                        {call.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {call.scheduledDate || "-"}
                    </td>
                  </tr>
                ))}

              {serviceCalls.length === 0 && (
                <tr>
                  <td
                    colSpan={6}
                    className="px-4 py-10 text-center text-slate-500"
                  >
                    No service calls assigned.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="mt-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h3 className="mb-5 text-lg font-bold">Recent Attendance</h3>

        <div className="overflow-hidden rounded-xl border border-slate-200">
          <table className="w-full">
            <thead className="bg-slate-50">
              <tr>
                <th className="px-4 py-3 text-left text-sm">Date</th>
                <th className="px-4 py-3 text-left text-sm">Status</th>
                <th className="px-4 py-3 text-left text-sm">Check In</th>
                <th className="px-4 py-3 text-left text-sm">Check Out</th>
              </tr>
            </thead>
            <tbody>
              {attendance.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-4 py-10 text-center text-slate-500">
                    No attendance records yet.
                  </td>
                </tr>
              ) : (
                attendance.slice(0, 15).map((a) => (
                  <tr key={a.id} className="border-t border-slate-100">
                    <td className="px-4 py-3 text-sm">{a.attendanceDate}</td>
                    <td className="px-4 py-3">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-semibold ${
                          a.status === "PRESENT"
                            ? "bg-green-100 text-green-700"
                            : a.status === "ABSENT"
                            ? "bg-red-100 text-red-700"
                            : a.status === "LEAVE"
                            ? "bg-orange-100 text-orange-700"
                            : "bg-slate-100 text-slate-600"
                        }`}
                      >
                        {a.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {a.checkInTime
                        ? new Date(a.checkInTime).toLocaleTimeString("en-GB", {
                            hour: "2-digit",
                            minute: "2-digit",
                          })
                        : "-"}
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {a.checkOutTime
                        ? new Date(a.checkOutTime).toLocaleTimeString("en-GB", {
                            hour: "2-digit",
                            minute: "2-digit",
                          })
                        : "-"}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="mt-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <h3 className="mb-3 text-lg font-bold">Notes</h3>
        <p className="text-slate-600">{employee.notes || "No notes added."}</p>
      </div>
    </DashboardLayout>
  );
}

function Card({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <h3 className="mb-5 text-lg font-bold">{title}</h3>
      {children}
    </div>
  );
}

function Info({ label, value }: { label: string; value?: string }) {
  return (
    <div className="mb-4">
      <p className="text-xs font-semibold uppercase tracking-wide text-slate-400">
        {label}
      </p>
      <p className="mt-1 font-medium text-slate-900">{value || "-"}</p>
    </div>
  );
}