"use client";

import { useState, useEffect, useCallback } from "react";
import { fetchWrapper } from "@/api/fetchWrapper";
import { BASE_URL } from "@/api/config";
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
import Button from "@/components/ui/button/Button";
import { useRouter } from "next/navigation";
import Badge from "@/components/ui/badge/Badge";
import { useDebounce } from "@/hooks/useDebounce";
import { useModal } from "@/hooks/useModal";
import ChangePasswordModal from "@/components/modals/ChangePasswordModal";
import { toast } from "react-hot-toast";
import Label from "@/components/form/Label";
import Input from "@/components/form/input/InputField";
import Select from "@/components/form/Select";
import ComponentCard from "@/components/common/ComponentCard";

// Define the Doctor interface based on expected API response
interface Doctor {
  id: string;
  first_name: string;
  last_name: string;
  email: string;
  created_at: string; // Assuming ISO date string
  is_active: boolean;
}

const DoctorsPage = () => {
  const router = useRouter();
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedDoctorId, setSelectedDoctorId] = useState<string | null>(null);

  const { isOpen, openModal, closeModal } = useModal();

  // State for search and filtering
  const [filters, setFilters] = useState({
    name: "",
    is_active: "",
  });

  const debouncedFilters = useDebounce(filters, 500);

  const fetchDoctors = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      Object.entries(debouncedFilters).forEach(([key, value]) => {
        if (value) {
          params.append(key, value);
        }
      });
      params.append("role", "DOCTOR");

      const response = await fetchWrapper(
        `${BASE_URL}/api/users/?${params.toString()}`
      );
      if (response.ok) {
        const data = await response.json();
        setDoctors(data.results || []);
      } else {
        throw new Error("بارگیری پزشکان با مشکل مواجه شد.");
      }
    } catch (err: unknown) {
      if (err instanceof Error) {
        setError(err.message || "خطا در بارگذاری پزشکان.");
      } else {
        setError("خطا در بارگذاری پزشکان.");
      }
    } finally {
      setLoading(false);
    }
  }, [debouncedFilters]);

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

  const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFilters((prev) => ({ ...prev, [name]: value }));
  };

  const handleSelectFilterChange = (name: string, value: string) => {
    setFilters((prev) => ({ ...prev, [name]: value }));
  };

  const handleNewDoctor = () => {
    router.push("/doctors/new");
  };

  const handleEdit = (doctorId: string) => {
    router.push(`/doctors/${doctorId}`);
  };

  const handleDelete = async (doctorId: string) => {
    if (window.confirm("آیا از حذف پزشک مطمئن هستید؟")) {
      try {
        const response = await fetchWrapper(`${BASE_URL}/api/users/${doctorId}/`, {
          method: "DELETE",
        });
        if (response.ok) {
          fetchDoctors();
        } else {
          toast.error("حذف پزشک با خطا مواجه شد.");
        }
      } catch {
        toast.error("خطا در حذف پزشک رخ داد.");
      }
    }
  };

  const handleChangePassword = (doctorId: string) => {
    setSelectedDoctorId(doctorId);
    openModal();
  };

  return (
    <>
      <PageBreadcrumb pageTitle="پزشکان" />

      <ComponentCard title="لیست پزشکان">
        <div className="flex justify-between items-center mb-6">
          <div className="flex space-x-4">
            <div>
              <Label htmlFor="name">جستجو بر اساس نام</Label>
              <Input
                type="text"
                name="name"
                id="name"
                placeholder="جستجو بر اساس نام..."
                value={filters.name}
                onChange={handleFilterChange}
              />
            </div>
            <div>
              <Label htmlFor="is_active">وضعیت</Label>
              <div className="relative">
                <Select
                  options={[
                    { value: "", label: "همه" },
                    { value: "true", label: "فعال" },
                    { value: "false", label: "غیرفعال" }
                  ]}
                  placeholder="انتخاب وضعیت"
                  value={filters.is_active}
                  onChange={(value) => handleSelectFilterChange("is_active", value)}
                />
              </div>
            </div>
          </div>
          <Button onClick={handleNewDoctor}>
            ایجاد پزشک جدید
          </Button>
        </div>

        {loading && <div>در حال بارگذاری پزشکان...</div>}
        {error && <div className="text-red-500">{error}</div>}

        {!loading && !error && (
          <div className="max-w-full overflow-x-auto">
            <table className="w-full table-auto">
              <thead>
                <tr className="bg-gray-2 text-left dark:bg-meta-4">
                  <th className="min-w-[220px] py-4 px-4 font-medium text-black dark:text-white xl:pl-11">
                    نام و نام خانوادگی
                  </th>
                  <th className="min-w-[120px] py-4 px-4 font-medium text-black dark:text-white">
                    تاریخ پیوستن
                  </th>
                  <th className="py-4 px-4 font-medium text-black dark:text-white">
                    وضعیت
                  </th>
                  <th className="py-4 px-4 font-medium text-black dark:text-white">
                    عملیات ها
                  </th>
                </tr>
              </thead>
              <tbody>
                {doctors.map((doctor) => (
                  <tr key={doctor.id}>
                    <td className="border-b border-[#eee] py-5 px-4 pl-9 dark:border-strokedark xl:pl-11">
                      <h5 className="font-medium text-black dark:text-white">
                        {doctor.first_name} {doctor.last_name}
                      </h5>
                      <p className="text-sm text-gray-500 dark:text-gray-400">{doctor.email}</p>
                    </td>
                    <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">
                      <p className="text-black dark:text-white">
                        {new Date(doctor.created_at).toLocaleDateString()}
                      </p>
                    </td>
                    <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">
                      <Badge color={doctor.is_active ? "success" : "error"}>
                        {doctor.is_active ? "فعال" : "غیرفعال"}
                      </Badge>
                    </td>
                    <td className="border-b border-[#eee] py-5 px-4 dark:border-strokedark">
                      <div className="flex items-center space-x-3.5">
                        <Button size="sm" variant="outline" onClick={() => handleEdit(doctor.id)}>ویرایش</Button>
                        <Button size="sm" variant="outline" onClick={() => handleChangePassword(doctor.id)}>تغییر رمز عبور</Button>
                        <Button size="sm" className="bg-red-500 hover:bg-red-600 text-white" onClick={() => handleDelete(doctor.id)}>حذف</Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </ComponentCard>
      <ChangePasswordModal isOpen={isOpen} onClose={closeModal} userId={selectedDoctorId} />
    </>
  );
};

export default DoctorsPage;