import { useRouter } from "next/navigation";
import { useIdiReportStore } from "@/store/idiReportStore";
import { useEffect, useState } from "react";
import { toast } from "react-toastify";
import {
  getJurorById,
  runIdiReport,
} from "@/services/jurorsService";
// import IdiReportDisplay from "./Idireportdisplay";


const formatUSPhone = (value = "") => {
  if (!value) return "";

  const digits = String(value).replace(/\D/g, "").slice(0, 10);

  if (digits.length <= 3) return digits;
  if (digits.length <= 6)
    return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;

  return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
};

export default function RunIdiReportModal({
  jurorId,
  isComprehensive = false,
  onClose,
}) {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [errors, setErrors] = useState({});

  // Holds the raw API response once a report has been generated.
  // const [reportResult, setReportResult] = useState(null);
  // Toggles between the "input form" view and the "report result" view.
  // const [showReport, setShowReport] = useState(false);
  const router = useRouter();
  const setReportResponse = useIdiReportStore((s) => s.setReportResponse);

  const [form, setForm] = useState({
    first_name: "",
    middle_name: "",
    last_name: "",
    birthdate: "",
    max_age: "",
    address: "",
    city: "",
    state: "",
    county: "",
    zipcode: "",
    phone_number: "",
  });

  useEffect(() => {
    if (isComprehensive) {
      // Clear all fields for manual entry
      setLoading(false);

      setForm({
        first_name: "",
        middle_name: "",
        last_name: "",
        birthdate: "",
        max_age: "",
        address: "",
        city: "",
        state: "",
        county: "",
        zipcode: "",
        phone_number: "",
      });

      return;
    }

    if (jurorId) {
      loadJuror();
    }
  }, [jurorId, isComprehensive]);

  const loadJuror = async () => {
    try {
      setLoading(true);

      const res = await getJurorById(jurorId);

      const data = res?.data || res;

      setForm({
        first_name: data.first_name || "",
        middle_name: data.middle_name || "",
        last_name: data.last_name || "",
        birthdate: data.date_of_birth || "",
        max_age: data.age || 52,
        address: data.street_address || "",
        city: data.city || "",
        state: data.state_details?.name || "",
        county: data.county || "",
        zipcode: data.zipcode || "",
        phone_number:
          formatUSPhone(data.primary_phone) ||
          formatUSPhone(data.cell_phone) ||
          "",
      });
    } catch (err) {
      toast.error("Failed to load juror details.");
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setForm((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));

    setErrors((prev) => ({
      ...prev,
      [e.target.name]: "",
    }));
  };

  // const generateReport = async () => {
  //   try {
  //     setSaving(true);

  //     const payload = {
  //       ...(isComprehensive ? {} : { juror_id: jurorId }),
  //       first_name: form.first_name,
  //       middle_name: form.middle_name,
  //       last_name: form.last_name,
  //       birthdate: form.birthdate,
  //       max_age: Number(form.max_age),
  //       address: form.address,
  //       city: form.city,
  //       state: form.state,
  //       county: form.county,
  //       zipcode: form.zipcode,
  //       phone_number: form.phone_number,
  //     };

  //     const res = await runIdiReport(payload);

  //     // `runIdiReport` returns the raw axios response, so the actual
  //     // API payload (the { status, message, data: { result } } object
  //     // shown in the logs) lives at `res.data`, not `res` itself.
  //     const payloadData = res?.data ?? res;

  //     // Store the result and switch the modal into "view report" mode.
  //     setReportResult(payloadData);
  //     setShowReport(true);

  //     toast.success("IDI Report generated successfully.");

  //     // Note: we no longer call onClose() here — closing immediately would
  //     // unmount the modal before the user ever sees the report. Let them
  //     // close it manually (via the X button) once they're done reviewing.
  //   } catch (err) {
  //     toast.error(
  //       err?.response?.data?.message ||
  //       "Failed to generate IDI report."
  //     );
  //   } finally {
  //     setSaving(false);
  //   }
  // };

  const validateForm = () => {
    const newErrors = {};

    if (!form.first_name.trim()) newErrors.first_name = "First name is required.";
    if (!form.last_name.trim()) newErrors.last_name = "Last name is required.";
    if (!form.state.trim()) newErrors.state = "State is required.";

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const generateReport = async () => {
    if (!validateForm()) return;
    try {
      setSaving(true);

      const payload = {
        ...(isComprehensive ? {} : { juror_id: jurorId }),
        first_name: form.first_name,
        middle_name: form.middle_name,
        last_name: form.last_name,
        birthdate: form.birthdate,
        max_age: Number(form.max_age),
        address: form.address,
        city: form.city,
        state: form.state,
        county: form.county,
        zipcode: form.zipcode,
        phone_number: form.phone_number,
      };

      const res = await runIdiReport(payload);
      const payloadData = res?.data ?? res;

      // Try to pull an id out of the response for the URL (fallback to jurorId).
      const reportId =
        payloadData?.data?.data?.id ??
        payloadData?.data?.id ??
        payloadData?.id ??
        jurorId;

      // Put the full report payload in the shared store.
      setReportResponse(payloadData);

      // toast.success("IDI Report generated successfully.");

      onClose();
      window.open(`/idireport/juror/${reportId}`, "_blank", "noopener=false,noreferrer=false");
    } catch (err) {
      toast.error(
        err?.response?.data?.message ||
        "Failed to generate IDI report."
      );
    } finally {
      setSaving(false);
    }
  };
  return (
    <div className="modal fade show" style={{ display: "block" }}>
      <div className="modal-dialog modal-lg modal-dialog-centered">
        <div className="modal-content editProfilepopup">

          <div className="modal-header mb-3">
            <div className="d-block">
              {/* <h5 className="modal-title">
                {showReport ? "IDI Report" : "Run IDI Report"}
              </h5> */}
              <h5 className="modal-title">Run IDI Report</h5>
              {/* {!showReport && (
                <p>Verify the information before generating the IDI report.</p>
              )} */}
              <p>Verify the information before generating the IDI report.</p>
            </div>

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

          <div className="modal-body">

            {/* {showReport ? (
              // ---------------- Report result view ----------------
              <IdiReportDisplay reportResponse={reportResult} />
            ) : loading ? (
              <p>Loading...</p>
            ) : ( */}
            {/* // ---------------- Input form view ---------------- */}
            <div className="row">

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  First Name <span className="text-danger">*</span>
                </label>

                <input
                  className={`form-control ${errors.first_name ? "is-invalid" : ""}`}
                  name="first_name"
                  value={form.first_name}
                  onChange={handleChange}
                />
                {errors.first_name && (
                  <div className="text-danger mt-1 text-start" style={{ fontSize: "0.85rem" }}>
                    {errors.first_name}
                  </div>
                )}
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Middle Name
                </label>

                <input
                  className="form-control"
                  name="middle_name"
                  value={form.middle_name}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Last Name <span className="text-danger">*</span>
                </label>

                <input
                  className={`form-control ${errors.last_name ? "is-invalid" : ""}`}
                  name="last_name"
                  value={form.last_name}
                  onChange={handleChange}
                />
                {errors.last_name && (
                  <div className="text-danger mt-1 text-start" style={{ fontSize: "0.85rem" }}>
                    {errors.last_name}
                  </div>
                )}
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Birthdate
                </label>

                <input
                  type="text"
                  className="form-control"
                  placeholder="MM-DD-YYYY"
                  name="birthdate"
                  value={form.birthdate}
                  onChange={handleChange}
                  onBlur={(e) => {
                    const value = e.target.value.trim();

                    if (/^\d{4}$/.test(value)) {
                      setForm((prev) => ({
                        ...prev,
                        birthdate: `XX-XX-${value}`,
                      }));
                    }
                  }}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Max Age (&gt;18)
                </label>

                <input
                  type="number"
                  className="form-control"
                  name="max_age"
                  value={form.max_age}
                  onChange={handleChange}
                  min={18}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Phone Number
                </label>

                <input
                  className="form-control"
                  name="phone_number"
                  placeholder="Enter phone number"
                  value={form.phone_number}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      phone_number: formatUSPhone(e.target.value),
                    }))
                  }
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Current Address
                </label>

                <input
                  className="form-control"
                  name="address"
                  value={form.address}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Current City
                </label>

                <input
                  className="form-control"
                  name="city"
                  value={form.city}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Current State <span className="text-danger">*</span>
                </label>

                <input
                  className={`form-control ${errors.state ? "is-invalid" : ""}`}
                  name="state"
                  value={form.state}
                  onChange={handleChange}
                />
                {errors.state && (
                  <div className="text-danger mt-1 text-start" style={{ fontSize: "0.85rem" }}>
                    {errors.state}
                  </div>
                )}
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  County
                </label>

                <input
                  className="form-control"
                  name="county"
                  value={form.county}
                  onChange={handleChange}
                />
              </div>

              <div className="col-md-6 mb-3">
                <label className="d-block text-start">
                  Zipcode
                </label>

                <input
                  className="form-control"
                  name="zipcode"
                  value={form.zipcode}
                  onChange={handleChange}
                />
              </div>

            </div>
            {/* )} */}

          </div>

          {/* {!showReport && ( */}
          <div className="modal-footer d-flex justify-content-center">
            <button
              className="btn btn-primary"
              style={{
                width: "80%",
                textAlign: "center",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
              onClick={generateReport}
              disabled={saving}
            >
              {saving ? "Generating..." : "Generate"}
            </button>
          </div>
          {/* )} */}

        </div>
      </div>
    </div>
  );
}