"use client";
import React, { useEffect, useState } from "react";
import { Plus, Pencil, Trash2, Calendar as CalendarIcon, Search } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
  fetchHolidays,
  createHoliday,
  updateHoliday,
  deleteHoliday,
  Holiday,
} from "@/store/slices/holidaySlice";
import DataTable from "react-data-table-component";
import { useModal } from "@/hooks/useModal";
import { Modal } from "@/components/common/modal";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";

interface HolidayFormData {
  title: string;
  type?: string;
  startDate: string;
  endDate: string;
}

export default function HolidaysPage() {
  const dispatch = useAppDispatch();
  const { holidays, loading } = useAppSelector((state) => state.holidays);
  const { isOpen, openModal, closeModal } = useModal();
  const { isOpen: isDeleteModalOpen, openModal: openDeleteModal, closeModal: closeDeleteModal } = useModal();
  const [selectedHoliday, setSelectedHoliday] = useState<Holiday | null>(null);
  const [holidayToDelete, setHolidayToDelete] = useState<Holiday | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [resetPaginationToggle, setResetPaginationToggle] = useState(false);
  const [activeTab, setActiveTab] = useState<"holidays" | "weekoffs">("holidays");
  const [searchText, setSearchText] = useState("");

  const { register, handleSubmit, reset, formState: { errors } } = useForm<HolidayFormData>();

  useEffect(() => {
    const timer = setTimeout(() => {
      dispatch(fetchHolidays({ search: searchText }));
    }, 500);
    return () => clearTimeout(timer);
  }, [dispatch, searchText]);

  const handleAdd = () => {
    setSelectedHoliday(null);
    if (activeTab === "weekoffs") {
      reset({ title: "Week-off", type: "WEEK_OFF", startDate: "", endDate: "" });
    } else {
      reset({ title: "", type: "HOLIDAY", startDate: "", endDate: "" });
    }
    openModal();
  };

  const handleEdit = (holiday: Holiday) => {
    setSelectedHoliday(holiday);
    reset({
      title: holiday.title,
      type: holiday.type || (activeTab === "weekoffs" ? "WEEK_OFF" : "HOLIDAY"),
      startDate: new Date(holiday.startDate).toISOString().split('T')[0],
      endDate: new Date(holiday.endDate).toISOString().split('T')[0],
    });
    openModal();
  };

  const handleDelete = (holiday: Holiday) => {
    setHolidayToDelete(holiday);
    openDeleteModal();
  };

  const confirmDelete = async () => {
    if (holidayToDelete) {
      try {
        await dispatch(deleteHoliday(holidayToDelete.id)).unwrap();
        toast.success("Holiday deleted successfully");
        closeDeleteModal();
        setHolidayToDelete(null);
      } catch (error: any) {
        toast.error(error || "Failed to delete holiday");
      }
    }
  };

  const onSubmit = async (data: HolidayFormData) => {
    // Force the type based on the active tab if not set correctly
    const finalData = { ...data, type: activeTab === "weekoffs" ? "WEEK_OFF" : "HOLIDAY" };

    // For week-offs, if they only enter start date, set end date to match
    if (activeTab === "weekoffs" && !finalData.endDate) {
      finalData.endDate = finalData.startDate;
    }

    try {
      if (selectedHoliday) {
        await dispatch(updateHoliday({ id: selectedHoliday.id, data: finalData })).unwrap();
        toast.success("Holiday updated successfully");
      } else {
        await dispatch(createHoliday(finalData)).unwrap();
        toast.success("Holiday created successfully");
      }
      closeModal();
      dispatch(fetchHolidays({ search: searchText }));
    } catch (error: any) {
      toast.error(error || "Failed to save holiday");
    }
  };

  const filteredHolidays = holidays.filter((h) => {
    const matchesTab = activeTab === "weekoffs" ? h.type === "WEEK_OFF" : h.type !== "WEEK_OFF";
    const matchesSearch = h.title?.toLowerCase().includes(searchText.toLowerCase()) || false;
    return matchesTab && matchesSearch;
  });

  const columns = [
    {
      name: "S.No.",
      selector: (_row: Holiday, index?: number) => (index !== undefined ? (currentPage - 1) * rowsPerPage + index + 1 : 0),
      sortable: false,
      width: "80px",
    },
    {
      name: "Title",
      selector: (row: Holiday) => row.title,
      sortable: true,
    },
    {
      name: activeTab === "weekoffs" ? "Date" : "Start Date",
      selector: (row: Holiday) => new Date(row.startDate).toLocaleDateString(),
      sortable: true,
    },
    ...(activeTab === "holidays" ? [{
      name: "End Date",
      selector: (row: Holiday) => new Date(row.endDate).toLocaleDateString(),
      sortable: true,
    }] : []),
    {
      name: "Actions",
      cell: (row: Holiday) => (
        <div className="flex gap-2">
          <button
            onClick={() => handleEdit(row)}
            className="flex h-8 w-8 items-center justify-center rounded-lg bg-orange-50 text-orange-500 hover:bg-orange-100 transition-colors"
          >
            <Pencil size={16} />
          </button>
          <button
            onClick={() => handleDelete(row)}
            className="flex h-8 w-8 items-center justify-center rounded-lg bg-red-50 text-red-500 hover:bg-red-100 transition-colors"
          >
            <Trash2 size={16} />
          </button>
        </div>
      ),
      width: "150px",
    },
  ];

  return (
    <div className="min-h-screen">
      <div className="mx-auto max-w-[1500px] space-y-6">
        {/* Header */}
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <div>
            <h1 className="text-xl lg:text-2xl font-medium text-brand-950">Holidays List</h1>
            <p className="text-sm text-gray-500 mt-1">Manage company holidays and off-days</p>
          </div>
          <button
            onClick={handleAdd}
            className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-2.5 lg:px-4 py-2.5 lg:py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
          >
            <Plus size={20} />
            <span className="hidden lg:inline-block">Add {activeTab === "weekoffs" ? "Day Holiday" : "Holiday"}</span>
          </button>
        </div>

        <div className="flex space-x-2 border-b border-gray-200">
          <button
            onClick={() => setActiveTab("holidays")}
            className={`py-3 px-6 text-sm font-medium transition-colors ${activeTab === "holidays"
                ? "border-b-2 border-brand-950 text-brand-950"
                : "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
              }`}
          >
            Holidays
          </button>
          <button
            onClick={() => setActiveTab("weekoffs")}
            className={`py-3 px-6 text-sm font-medium transition-colors ${activeTab === "weekoffs"
                ? "border-b-2 border-brand-950 text-brand-950"
                : "text-gray-500 hover:text-gray-700 hover:bg-gray-50"
              }`}
          >
            Day Holidays (Week-offs)
          </button>
        </div>

        {/* Table Container */}
        <div className="rounded-xl bg-white p-6 shadow-theme-md">
          <div className="md:border border-gray-200 md:rounded-lg overflow-hidden">
            <div className="flex items-center justify-between md:border-b md:px-4 pb-4 md:py-4">
              <div className="hidden md:flex items-center gap-2">
                <span className="text-sm font-normal text-gray-500 block">Show</span>
                <div className="relative">
                  <select
                    value={rowsPerPage}
                    onChange={(e) => {
                      setRowsPerPage(Number(e.target.value));
                      setCurrentPage(1);
                      setResetPaginationToggle(!resetPaginationToggle);
                    }}
                    className="w-full rounded-lg border appearance-none px-3 py-2 pr-8 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  >
                    <option value={10}>10</option>
                    <option value={20}>20</option>
                    <option value={30}>30</option>
                    <option value={50}>50</option>
                  </select>
                  <span className="absolute text-gray-500 -translate-y-1/2 pointer-events-none right-2 top-1/2">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none">
                      <path stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M4.792 7.396 10 12.604l5.208-5.208"></path>
                    </svg>
                  </span>
                </div>
                <span className="text-sm font-normal text-gray-500">entries</span>
              </div>
              <div className="flex items-center gap-4 w-full sm:w-auto">
                <div className="relative block w-full sm:w-auto">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" size={16} />
                  <input
                    type="text"
                    placeholder="Search holidays..."
                    value={searchText}
                    onChange={(e) => {
                      setSearchText(e.target.value);
                      setCurrentPage(1);
                    }}
                    className="h-11 w-full rounded-lg border appearance-none py-2.5 pl-9 pr-4 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 border-gray-300 outline-none"
                  />
                </div>
              </div>
            </div>

            <div className="overflow-x-auto">
              <DataTable
                key={`table-${rowsPerPage}`}
                columns={columns}
                data={filteredHolidays.slice((currentPage - 1) * rowsPerPage, currentPage * rowsPerPage)}
                progressPending={loading}
                pagination
                paginationServer
                paginationTotalRows={filteredHolidays.length}
                paginationResetDefaultPage={resetPaginationToggle}
                onChangePage={(page) => setCurrentPage(page)}
                onChangeRowsPerPage={(newPerPage, page) => {
                  setRowsPerPage(newPerPage);
                  setCurrentPage(page);
                  setResetPaginationToggle(!resetPaginationToggle);
                }}
                paginationComponentOptions={{ noRowsPerPage: true }}
                responsive
                highlightOnHover
                customStyles={{
                  headRow: {
                    style: {
                      backgroundColor: '#ffffff',
                      color: '#1E293B',
                      fontWeight: 600,
                      fontSize: '14px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                  rows: {
                    style: {
                      fontSize: '14px',
                      color: '#475569',
                      minHeight: '60px',
                      borderBottom: '1px solid #F1F5F9',
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>

        <Modal isOpen={isOpen} onClose={closeModal} className="max-w-md p-6">
          <h2 className="text-xl font-bold mb-4">
            {selectedHoliday ? `Edit ${activeTab === "weekoffs" ? "Day Holiday" : "Holiday"}` : `Add ${activeTab === "weekoffs" ? "Day Holiday" : "Holiday"}`}
          </h2>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Title
              </label>
              <input
                {...register("title", { required: "Title is required" })}
                className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500"
                placeholder={activeTab === "weekoffs" ? "E.g., Week-off" : "E.g., Christmas"}
              />
              {errors.title && (
                <p className="text-red-500 text-xs mt-1">{errors.title.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                {activeTab === "weekoffs" ? "Date" : "Start Date"}
              </label>
              <div className="relative cursor-pointer" onClick={(e) => {
                const input = e.currentTarget.querySelector('input[type="date"]') as HTMLInputElement;
                if (input && typeof input.showPicker === 'function') {
                  input.showPicker();
                }
              }}>
                <input
                  type="date"
                  {...register("startDate", { required: "Date is required" })}
                  className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 cursor-pointer [&::-webkit-calendar-picker-indicator]:hidden"
                  style={{ WebkitAppearance: 'none' }}
                />
                <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400">
                  <CalendarIcon size={18} />
                </div>
              </div>
              {errors.startDate && (
                <p className="text-red-500 text-xs mt-1">{errors.startDate.message}</p>
              )}
            </div>

            {activeTab === "holidays" && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  End Date
                </label>
                <div className="relative cursor-pointer" onClick={(e) => {
                  const input = e.currentTarget.querySelector('input[type="date"]') as HTMLInputElement;
                  if (input && typeof input.showPicker === 'function') {
                    input.showPicker();
                  }
                }}>
                  <input
                    type="date"
                    {...register("endDate", { required: "End date is required" })}
                    className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500 cursor-pointer [&::-webkit-calendar-picker-indicator]:hidden"
                    style={{ WebkitAppearance: 'none' }}
                  />
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400">
                    <CalendarIcon size={18} />
                  </div>
                </div>
                {errors.endDate && (
                  <p className="text-red-500 text-xs mt-1">{errors.endDate.message}</p>
                )}
              </div>
            )}

            <div className="flex justify-end gap-3 mt-6">
              <button
                type="button"
                onClick={closeModal}
                className="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-brand-950 text-white rounded-lg shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 transition-colors"
              >
                {selectedHoliday ? "Update" : "Create"}
              </button>
            </div>
          </form>
        </Modal>

        {/* Delete Confirmation Modal */}
        <Modal isOpen={isDeleteModalOpen} onClose={closeDeleteModal} showCloseButton={false} className="max-w-[450px] m-4">
          <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
            <div className="px-2 text-center">
              <h4 className="text-xl lg:text-2xl font-semibold text-brand-950 mb-2">
                Confirm Delete
              </h4>
              <p className="mb-6 text-sm text-gray-500 lg:mb-7">
                Are you sure you want to delete <span className="font-semibold pl-1 text-gray-800">{holidayToDelete?.title}</span>?
              </p>
            </div>
            <div className="flex items-center gap-3 mt-6 justify-center">
              <button
                type="button"
                onClick={closeDeleteModal}
                className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-100 transition-colors"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={confirmDelete}
                className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500"
              >
                Delete
              </button>
            </div>
          </div>
        </Modal>
      </div>
    </div>
  );
}
