"use client";

import { useEffect, useState } from "react";

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

type Event = {
  eventId: number;
  title: string;
  description: string;
  venue: string;
  date: string;
  startTime: string;
  endTime: string;
  // image?: string;
};

const columns = [
  {
    header: "Event No.",
    accessor: "eventId",
    className: "hidden md:table-cell",
  },
  { header: "Title", accessor: "title" },
  {
    header: "Description",
    accessor: "description",
    className: "hidden lg:table-cell",
  },
  { header: "Venue", accessor: "venue", className: "hidden md:table-cell" },
  { header: "Date", accessor: "date", className: "hidden md:table-cell" },
  {
    header: "Starts",
    accessor: "startTime",
    className: "hidden md:table-cell",
  },
  { header: "Ends", accessor: "endTime", className: "hidden md:table-cell" },
  { header: "Actions", accessor: "actions" },
];

const Events = () => {
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [role, setRole] = useState<string>("");

  useEffect(() => {
    const fetchEvents = async () => {
      try {
        const data = await getEvents();
        setEvents(data);
      } catch (error: any) {
        console.log("Error fetching events:", {
          message: error?.message,
          status: error?.response?.status,
          data: error?.response?.data,
          fullError: error,
        });
      } finally {
        setLoading(false);
      }
    };

    fetchEvents();
    setRole(localStorage.getItem("role") || "user");
    // setRole("admin");
  }, []);
  // Mock role fetching (Replace with real authentication logic)

  const renderRow = (item: Event) => (
    <tr
      key={item.eventId}
      className="border-b border-gray-200 even:bg-slate-50 text-sm hover:bg-slate-50"
    >
      <td className="hidden md:table-cell">{item.eventId}</td>
      <td className="flex items-center gap-4 p-4">
        <div className="flex flex-col">
          <h3 className="font-semibold">{item.title}</h3>
        </div>
      </td>
      <td className="hidden md:table-cell">{item.description}</td>
      <td className="hidden md:table-cell">{item.venue}</td>
      <td className="hidden md:table-cell">{item.date}</td>
      <td className="hidden md:table-cell">{item.startTime}</td>
      <td className="hidden md:table-cell">{item.endTime}</td>
      <td>
        <div className="flex items-center gap-2">
          <Link href={`/dashboard/list/events/${item.eventId}`}>
            <button className="w-8 h-8 flex items-center justify-center rounded-full bg-white">
              <Image src="/view.png" alt="" width={16} height={16} />
            </button>
          </Link>
          {role === "admin" && (
            <>
              <FormModal table="Events" type="update" data={item} />
              <FormModal table="Events" type="delete" id={item.eventId} />
            </>
          )}
        </div>
      </td>
    </tr>
  );

  return (
    <div className="bg-white p-4 rounded-md flex-1 m-4 mt-4">
      {/* TOP */}
      <div className="flex items-center justify-between">
        <h1 className="hidden md:block text-lg font-semibold">Church Events</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="Events" type="create" />}
          </div>
        </div>
      </div>

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

export default Events;
