"use client";

import { useState, 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 Select from "@/components/form/Select";
import { Modal } from "@/components/ui/modal";
import { SERVICE_STATUSES } from "@/lib/prescription-statuses";

interface ChangeStatusModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  prescriptionId: number | null;
}

const ChangeStatusModal = ({ isOpen, onClose, onSuccess, prescriptionId }: ChangeStatusModalProps) => {
  const [serviceStatus, setServiceStatus] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!prescriptionId) return;

    setSubmitting(true);
    setError(null);

    try {
      const response = await fetchWrapper(`${BASE_URL}/api/prescriptions/${prescriptionId}/`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ service_status: serviceStatus }),
      });

      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="mb-4.5">
            <Label htmlFor="service_status">وضعیت خدمات</Label>
            <Select
              options={SERVICE_STATUSES.map(status => ({ value: status.value, label: status.label }))}
              placeholder="انتخاب وضعیت"
              value={serviceStatus}
              onChange={(value) => setServiceStatus(value)}
            />
        </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 ChangeStatusModal;
