import React, { useState } from "react";
import { toast } from "react-toastify";
import { assignUnassignedJurorsToAnalyst } from "@/services/jurorsService";

export default function AssignJurorsModal({
  caseId,
  analystId,
  onClose,
  onSuccess,
}) {
  console.log("caseId:", caseId);
  console.log("analystId:", analystId);
  const [numberAssigned, setNumberAssigned] = useState("");
  const [loading, setLoading] = useState(false);

  const handleChange = (e) => {
    const value = e.target.value.replace(/\D/g, "").slice(0, 3);
    setNumberAssigned(value);
  };

  const handleSubmit = async () => {
    if (!numberAssigned) {
      toast.error("Please enter the number of assigned jurors.");
      return;
    }

    const payload = {
      case_id: Number(caseId),
      analyst_id: Number(analystId),
      number_assigned: Number(numberAssigned),
    };

    try {
      const response = await assignUnassignedJurorsToAnalyst(payload);

      console.log(response.data);

      toast.success("Jurors assigned successfully.");

      onSuccess?.();
      onClose();
    } catch (error) {
      console.error(error);

      toast.error(error?.response?.data?.message || "Failed to assign jurors.");
    }
  };

  return (
    <div className="modal-backdrop">
      <div className="edit-juror-modal h-auto">
        <div className="modal-header">
          <div>
            <h3 className="m-0">Assign Jurors</h3>
            <p className="mb-0">Enter the number of jurors to assign.</p>
          </div>

          <button className="btn-close" onClick={onClose}></button>
        </div>

        <div className="modal-body">
          <div className="datafrm">
            <label>
              Number of Assigned Jurors <span style={{ color: "red" }}>*</span>
            </label>

            <input
              type="text"
              placeholder="Enter Number"
              value={numberAssigned}
              onChange={handleChange}
              maxLength={3}
            />
          </div>
        </div>

        <div className="modal-footer datafrmbtn">
          <button className="cancelbtn" onClick={onClose} disabled={loading}>
            Cancel
          </button>

          <button className="savebtn" onClick={handleSubmit} disabled={loading}>
            {loading ? "Submitting..." : "Submit"}
          </button>
        </div>
      </div>
    </div>
  );
}
