"use client";

import { useState, useEffect, FormEvent } from "react";
import { fetchWrapper } from "@/api/fetchWrapper";
import { BASE_URL } from "@/api/config";
import Button from "@/components/ui/button/Button";
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 { Modal } from "@/components/ui/modal";
import { usePrescriptionContext } from "@/context/PrescriptionContext";
import { useUser } from "@/context/UserContext";

interface NewPrescriptionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const NewPrescriptionModal = ({ isOpen, onClose, onSuccess }: NewPrescriptionModalProps) => {
  const { doctors, baseInsurances, supplementaryInsurances } = usePrescriptionContext();
  const { user } = useUser();
  
  const [formData, setFormData] = useState({
    patient_first_name: "",
    patient_last_name: "",
    patient_national_id: "",
    patient_base_insurance_issuer: "",
    patient_supplementary_insurance_issuer: "",
    prescription_number: "",
    doctor: "",
  });
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [doctorsOptions, setDoctorsOptions] = useState<{ value: string; label: string }[]>([]);
  const is_doctor = user?.role === "DOCTOR";

  useEffect(() => {
    if (!is_doctor) {
      setDoctorsOptions(doctors.map(doc => ({ value: doc.id, label: doc.full_name })));
    } else if (is_doctor && user) {
      setFormData((prev) => ({ ...prev, doctor: user.id }));
      setDoctorsOptions([{ value: user.id, label: user.full_name }]);
    }
  }, [doctors, is_doctor, user]);

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

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

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError(null);

    try {
      const response = await fetchWrapper(`${BASE_URL}/api/prescriptions/`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ...formData,
          patient_base_insurance_issuer: parseInt(formData.patient_base_insurance_issuer, 10),
          patient_supplementary_insurance_issuer: parseInt(formData.patient_supplementary_insurance_issuer, 10),
        }),
      });

      if (response.ok) {
        toast.success("نسخه با موفقیت ایجاد شد.");
        onSuccess();
        onClose();
      } else {
        const errorData = await response.json();
        const errorMessage = Object.entries(errorData)
          .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`)
          .join("\n");
        setError(errorMessage || "ایجاد نسخه با خطا مواجه شد.");
      }
    } catch (err: unknown) {
        if (err instanceof Error) {
            setError(err.message || "خطای غیرمنتظره‌ای رخ داد.");
        } else {
            setError("خطای غیرمنتظره‌ای رخ داد.");
        }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="max-w-[584px] p-5 lg:p-10">
      <form onSubmit={handleSubmit}>
        <h4 className="mb-6 text-lg font-medium text-gray-800 dark:text-white/90">
          ایجاد نسخه جدید
        </h4>

        {error && (
          <div className="mb-4 rounded-md bg-red-100 p-4 text-red-500">
            <pre>{error}</pre>
          </div>
        )}

        <div className="grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2">
          <div>
            <Label htmlFor="patient_first_name">نام بیمار</Label>
            <Input type="text" name="patient_first_name" id="patient_first_name" placeholder="نام بیمار" value={formData.patient_first_name} onChange={handleChange} />
          </div>
          <div>
            <Label htmlFor="patient_last_name">نام خانوادگی بیمار</Label>
            <Input type="text" name="patient_last_name" id="patient_last_name" placeholder="نام خانوادگی بیمار" value={formData.patient_last_name} onChange={handleChange} />
          </div>
          <div>
            <Label htmlFor="patient_national_id">شماره ملی بیمار</Label>
            <Input type="text" name="patient_national_id" id="patient_national_id" placeholder="شماره ملی بیمار" value={formData.patient_national_id} onChange={handleChange} required />
          </div>
          <div>
            <Label htmlFor="prescription_number">کد پیگیری</Label>
            <Input type="text" name="prescription_number" id="prescription_number" placeholder="کد پیگیری" value={formData.prescription_number} onChange={handleChange} required />
          </div>
          <div>
            <Label htmlFor="patient_base_insurance_issuer">بیمه پایه</Label>
            <Select
              options={baseInsurances.map(ins => ({ value: ins.id.toString(), label: ins.name }))}
              placeholder="انتخاب بیمه پایه"
              value={formData.patient_base_insurance_issuer}
              onChange={(value) => handleSelectChange("patient_base_insurance_issuer", value)}
            />
          </div>
          <div>
            <Label htmlFor="patient_supplementary_insurance_issuer">بیمه تکمیلی</Label>
            <Select
              options={supplementaryInsurances.map(ins => ({ value: ins.id.toString(), label: ins.name }))}
              placeholder="انتخاب بیمه تکمیلی"
              value={formData.patient_supplementary_insurance_issuer}
              onChange={(value) => handleSelectChange("patient_supplementary_insurance_issuer", value)}
            />
          </div>
          <div>
            <Label htmlFor="doctor">پزشک</Label>
            <Select
              options={doctorsOptions}
              placeholder="انتخاب پزشک"
              value={formData.doctor}
              onChange={(value) => handleSelectChange("doctor", value)}
              // disabled={user?.role === 'DOCTOR'}
            />
          </div>
        </div>

        <div className="flex items-center justify-end w-full gap-3 mt-6">
          <Button type="button" size="sm" variant="outline" onClick={onClose}>
            بستن
          </Button>
          <Button type="submit" size="sm" disabled={submitting}>
            {submitting ? "در حال ایجاد..." : "ایجاد نسخه"}
          </Button>
        </div>
      </form>
    </Modal>
  );
};

export default NewPrescriptionModal;
