"use client";

import { useEffect, useState } from "react";

import FormModal from "@/components/FormModal";
import Image from "next/image";
import Pagination from "@/components/Pagination";
import Table from "@/components/Table";
import TableSearch from "@/components/TableSearch";
import { getVisitors } from "../../../../../lib/api";

type Visitors = {
  visitorId: number;
  name: string;
  gender: string;
  email: string;
  mobile: string;
  dateOfVisit: string;
  idNumber: number;
};

const columns = [
  { header: "No.", accessor: "visitorId", className: "hidden md:table-cell" },
  { header: "Name", accessor: "name" },
  { header: "ID No.", accessor: "idNumber", className: "hidden md:table-cell" },
  { header: "Gender", accessor: "gender", className: "hidden lg:table-cell" },
  { header: "Email", accessor: "email", className: "hidden md:table-cell" },
  { header: "Mobile", accessor: "mobile", className: "hidden md:table-cell" },
  {
    header: "Date",
    accessor: "dateOfVisit",
    className: "hidden md:table-cell",
  },
  { header: "Actions", accessor: "actions" },
];

const VisitorsPage = () => {
  const [visitors, setVisitors] = useState<Visitors[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [role, setRole] = useState<string>("");

  useEffect(() => {
    const fetchVisitors = async () => {
      try {
        const data = await getVisitors();
        console.log("Fetched data:", data); // Log the raw response

        // Ensure data is an array
        if (!Array.isArray(data)) {
          throw new Error("Invalid data structure: Expected an array.");
        }

        const normalized = data.map((v: any) => ({
          visitorId: v.visitor_id,
          idNumber: v.id_number,
          name: v.name,
          gender: v.gender,
          email: v.email,
          mobile: v.mobile,
          dateOfVisit: new Date(v.date_of_visit).toLocaleDateString(), // Format date
        }));

        setVisitors(normalized);
      } catch (error) {
        console.error("Error fetching visitors:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchVisitors();
    setRole(localStorage.getItem("role") || "user");
  }, []);

  const renderRow = (item: Visitors) => (
    <tr
      key={item.visitorId}
      className="border-b border-gray-200 even:bg-slate-50 text-sm hover:bg-slate-50"
    >
      <td className="hidden md:table-cell">{item.visitorId}</td>

      <td className="flex items-center gap-4 p-4">
        <div className="flex flex-col">
          <h3 className="font-semibold">{item.name}</h3>
        </div>
      </td>
      <td className="hidden md:table-cell">{item.idNumber}</td>
      <td className="hidden md:table-cell">{item.gender}</td>
      <td className="hidden md:table-cell">{item.email}</td>
      <td className="hidden md:table-cell">{item.mobile}</td>
      <td className="hidden md:table-cell">{item.dateOfVisit}</td>
      <td>
        <div className="flex items-center gap-2">
          {role === "admin" && (
            <>
              <FormModal table="Visitors" type="update" data={item} />
              <FormModal table="Visitors" type="delete" id={item.visitorId} />
            </>
          )}
        </div>
      </td>
    </tr>
  );

  return (
    <div className="bg-white p-4 rounded-md flex-1 m-4 mt-4">
      <div className="flex items-center justify-between">
        <h1 className="hidden md:block text-lg font-semibold">Visitors</h1>
        <div className="flex flex-col md:flex-row items-center gap-4 w-full md:w-auto">
          <TableSearch />
          <div className="flex items-center gap-4 self-end">
            <button className="w-6 h-6 flex items-center justify-center rounded-full bg-red-300">
              <Image src="/filter.png" alt="Filter" width={14} height={14} />
            </button>
            <button className="w-6 h-6 flex items-center justify-center rounded-full bg-red-300">
              <Image src="/sort.png" alt="Sort" width={14} height={14} />
            </button>
            {role === "admin" && <FormModal table="Visitors" type="create" />}
          </div>
        </div>
      </div>

      {/* LIST */}
      {loading ? (
        <p className="text-center text-gray-500">Loading visitors...</p>
      ) : (
        <Table columns={columns} renderRow={renderRow} data={visitors} />
      )}
    </div>
  );
};

export default VisitorsPage;
