"use client";

import { BASE_URL } from "@/api/config";
import { useEffect, useState, useCallback } from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import Badge from "@/components/ui/badge/Badge";
import Button from "@/components/ui/button/Button";
import { ArrowPathIcon, TrashIcon, PencilIcon, EyeIcon, AdjustmentsHorizontalIcon } from "@heroicons/react/24/outline";
import PrescriptionDetailModal from "@/components/modals/PrescriptionDetailModal";
import { fetchWrapper } from "@/api/fetchWrapper";
import { useDebounce } from "@/hooks/useDebounce";
import { toast } from "react-hot-toast";
import { TrashBinIcon } from "@/icons";
import Label from "@/components/form/Label";
import Input from "@/components/form/input/InputField";
import Select from "@/components/form/Select";
import { usePrescriptionContext } from "@/context/PrescriptionContext";
import { useModal } from "@/hooks/useModal";
import NewPrescriptionModal from "@/components/modals/NewPrescriptionModal";
import { SERVICE_STATUSES } from "@/lib/prescription-statuses";
import ChangeStatusModal from "@/components/modals/ChangeStatusModal";
import Drawer from "@/components/ui/Drawer";
import FilterPanel from "./FilterPanel";

interface Prescription {
  id: number;
  patient_first_name: string;
  patient_last_name: string;
  patient_national_id: string;
  patient_base_insurance_issuer: number;
  patient_supplementary_insurance_issuer: number;
  prescription_number: number;
  doctor_name: string;
  created_at: string;
  created_by_name: string;
  service_status: string;
  service_status_updated_at: string;
}

interface ApiResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: Prescription[];
}

const PrescriptionsTable = () => {
  const { baseInsurances, supplementaryInsurances } = usePrescriptionContext();
  const { isOpen: isNewPrescriptionModalOpen, openModal: openNewPrescriptionModal, closeModal: closeNewPrescriptionModal } = useModal();
  const { isOpen: isChangeStatusModalOpen, openModal: openChangeStatusModal, closeModal: closeChangeStatusModal } = useModal();
  const { isOpen: isFilterDrawerOpen, openModal: openFilterDrawer, closeModal: closeFilterDrawer } = useModal();
  const [data, setData] = useState<ApiResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedPrescription, setSelectedPrescription] = useState<Prescription | null>(null);
  const [selectedPrescriptionId, setSelectedPrescriptionId] = useState<number | null>(null);
  const [filters, setFilters] = useState({
    doctor_name: "",
    patient_name: "",
    patient_national_id__icontains: "",
    prescription_number__icontains: "",
    service_status: "",
    patient_base_insurance_issuer: "",
    patient_supplementary_insurance_issuer: "",
  });

  const debouncedFilters = useDebounce(filters, 500); // 500ms delay

  const copyToClipboard = (text: string, fieldName: string) => {
    navigator.clipboard.writeText(text).then(
      () => {
        toast.success(`${fieldName} کپی شد.`);
      },
      (err) => {
        toast.error(`کپی ${fieldName} ناموفق بود.`);
        console.error("Could not copy text: ", err);
      }
    );
  };

  const fetchData = useCallback(async (
    currentPage: number,
    currentFilters: typeof filters,
    showLoading: boolean = true
  ) => {
    if (showLoading) setLoading(true);
    try {
      const params = new URLSearchParams();
      params.append("page", currentPage.toString());
      Object.entries(currentFilters).forEach(([key, value]) => {
        if (value) {
          params.append(key, value);
        }
      });

      const response = await fetchWrapper(
        `${BASE_URL}/api/prescriptions/?${params.toString()}`
      );
      if (response.ok) {
        const result = await response.json();
        setData(result);
        toast.success("داده‌های نسخه‌ها با موفقیت بارگذاری شد.");
      } else {
        setError("بارگذاری داده‌های نسخه‌ها ناموفق بود.");
      }
    } catch {
      setError("یک خطا در بارگذاری داده‌ها رخ داد.");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData(page, debouncedFilters, false);
  }, [page, debouncedFilters, fetchData]);

  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 handleClearFilters = () => {
    setFilters({
      doctor_name: "",
      patient_name: "",
      patient_national_id__icontains: "",
      prescription_number__icontains: "",
      patient_base_insurance_issuer: "",
      patient_supplementary_insurance_issuer: "",
      service_status: ""
    });
    toast.success("فیلتر ها با موفقیت حذف شدند")
  };

  const handleStatusChange = (id: number) => {
    setSelectedPrescriptionId(id);
    openChangeStatusModal();
  };

  const handleDelete = async (id: number) => {
    if (window.confirm("آیا از حذف این نسخه اطمینان دارید؟")) {
      try {
        const response = await fetchWrapper(`${BASE_URL}/api/prescriptions/${id}/`, {
          method: "DELETE",
          credentials: "include",
        });
        if (response.ok) {
          fetchData(page, filters);
        } else {
          toast.error("حذف نسخه ناموفق بود.");
        }
      } catch {
        toast.error("یک خطا در حذف نسخه رخ داد.");
      } finally {
        setLoading(false);
      }
    }
  };

  const handleViewDetails = (prescription: Prescription) => {
    setSelectedPrescription(prescription);
    setShowDetailModal(true);
  };

  const handleCloseModal = () => {
    setShowDetailModal(false);
    setSelectedPrescription(null);
  };

  const activeAdvancedFiltersCount = [
    filters.doctor_name,
    filters.prescription_number__icontains,
    filters.patient_base_insurance_issuer,
    filters.patient_supplementary_insurance_issuer,
  ].filter(Boolean).length;

  if (error) {
    return <div className="p-4 text-red-500 bg-red-100 rounded-md dark:text-white dark:bg-red-800">{error}</div>;
  }

  return (
    <div>
      <NewPrescriptionModal isOpen={isNewPrescriptionModalOpen} onClose={closeNewPrescriptionModal} onSuccess={() => fetchData(1, filters)} />
      <ChangeStatusModal isOpen={isChangeStatusModalOpen} onClose={closeChangeStatusModal} onSuccess={() => fetchData(page, filters)} prescriptionId={selectedPrescriptionId} />
      <Drawer isOpen={isFilterDrawerOpen} onClose={closeFilterDrawer}>
        <FilterPanel filters={filters} handleFilterChange={handleFilterChange} handleSelectFilterChange={handleSelectFilterChange} />
      </Drawer>

      <div className="flex flex-row md:grid-cols-1 gap-2 mb-2">
        <div className="grid grid-cols-2 gap-2">
          <Button
            variant="outline"
            onClick={() => fetchData(page, filters, false)}
            className="h-full"
          >
            <ArrowPathIcon className="w-6 h-6" />
            <span className="hidden sm:block ml-2">به‌روزرسانی لیست</span>
          </Button>
          <Button
            onClick={handleClearFilters}
            className="h-full"
            variant="outline"
          >
            <TrashBinIcon className="w-6 h-6" />
            <span className="hidden sm:block ml-2">حذف فیلترها</span>
          </Button>
        </div>
        <div className="w-fit ml-auto">
          <Button className="w-fit h-full" onClick={openNewPrescriptionModal}>افزودن نسخه جدید</Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:flex justify-between items-center gap-4 mt-4 md:mb-6">
        <div className="grid md:flex-grow grid-cols-1 gap-4 md:grid-cols-3 w-full">
          <div>
            <Label htmlFor="patient_name">نام بیمار</Label>
            <Input
              type="text"
              name="patient_name"
              id="patient_name"
              placeholder="نام بیمار"
              value={filters.patient_name}
              onChange={handleFilterChange}
            />
          </div>
          <div>
            <Label htmlFor="patient_national_id__icontains">کد ملی بیمار</Label>
            <Input
              type="text"
              name="patient_national_id__icontains"
              id="patient_national_id__icontains"
              placeholder="کد ملی بیمار"
              value={filters.patient_national_id__icontains}
              onChange={handleFilterChange}
            />
          </div>
          <div>
            <Label htmlFor="service_status">وضعیت</Label>
            <Select
              options={[
                { value: "", label: "همه" },
                ...SERVICE_STATUSES.map(s => ({ value: s.value, label: s.label }))
              ]}
              placeholder="انتخاب وضعیت"
              value={filters.service_status}
              onChange={(value) => handleSelectFilterChange("service_status", value)}
            />
          </div>
        </div>
        <div className="relative">
          <Button variant="outline" onClick={openFilterDrawer}>
            <AdjustmentsHorizontalIcon className="w-6 h-6" />
            <span className="hidden sm:block ml-2">فیلترهای بیشتر</span>
            {activeAdvancedFiltersCount > 0 && (
              <span className="absolute -top-2 -right-2 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-white text-xs">
                {activeAdvancedFiltersCount}
              </span>
            )}
          </Button>
        </div>
      </div>

      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-white/[0.05] dark:bg-white/[0.03]">
        <div className="max-w-full overflow-x-auto">
          {/* <div className="min-w-[1102px]"> */}
          <div className="min-w-full w-full">
            <Table className="table-fixed">
              <TableHeader className="border-b border-gray-100 dark:border-white/[0.05]">
                <TableRow>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">شماره</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">تاریخ ثبت</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">پزشک</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">کد ملی</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">بیمار</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white">وضعیت</TableCell>
                  <TableCell isHeader className="px-5 py-4 font-medium text-gray-900 dark:text-white w-fit">عملیات</TableCell>
                </TableRow>
              </TableHeader>
              <TableBody className="divide-y divide-gray-100 dark:divide-white/[0.05]">
                {loading ? (
                  <TableRow>
                    <TableCell colspan={7} className="text-center py-4 dark:text-white">
                      Loading...
                    </TableCell>
                  </TableRow>
                ) : data?.results.map((p, i) => {
                  const statusDisplay = SERVICE_STATUSES.find(s => s.value === p.service_status.toString()) || { label: p.service_status, color: 'light' };
                  return (
                    <TableRow key={p.id}>
                      <TableCell className="px-5 py-4 whitespace-nowrap text-center dark:text-white">{i + 1}</TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap text-center dark:text-white">{new Date(p.created_at).toLocaleString('fa-IR')}</TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap text-center dark:text-white">{p.doctor_name}</TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap text-center dark:text-white">{p.patient_national_id}</TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap text-center dark:text-white">
                        {p.patient_first_name} {p.patient_last_name}
                      </TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap">
                        <Badge color={statusDisplay.color}>
                          {statusDisplay.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="px-5 py-4 whitespace-nowrap">
                        <div className="flex space-x-2">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleViewDetails(p)}
                          >
                            <EyeIcon className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleStatusChange(p.id)}
                          >
                            <PencilIcon className="w-4 h-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="danger"
                            onClick={() => handleDelete(p.id)}
                          >
                            <TrashIcon className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
        </div>
      </div>
      <div className="flex justify-between mt-4">
        <Button
          onClick={() => setPage(page - 1)}
          disabled={!data?.previous}
        >
          قبلی
        </Button>
        <span className="dark:text-white">
          صفحه {page} از {data ? Math.ceil(data.count / 20) : 1}
        </span>
        <Button onClick={() => setPage(page + 1)} disabled={!data?.next}>
          بعدی
        </Button>
      </div>

      {selectedPrescription && (
        <PrescriptionDetailModal
          isOpen={showDetailModal}
          onClose={handleCloseModal}
          prescription={selectedPrescription}
          baseInsurances={baseInsurances}
          supplementaryInsurances={supplementaryInsurances}
          onCopyToClipboard={copyToClipboard}
        />
      )}
    </div>
  );
};

export default PrescriptionsTable;
