import React, { useEffect, useState } from "react";
import Layout from "@/Layout";
import { toast } from "react-toastify";
import { useParams } from 'next/navigation';
import useNavigate from '@/hooks/useNavigate';
import {
  getAllStates,
  getJurorById,
  updateJuror,
} from "@/services/jurorsService";
import Link from "next/link";
import CustomSelect from "@/components/common/CustomSelect";

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)}`;
};

const EditJuror = () => {
  const navigate = useNavigate();
  const { id } = useParams();

  const [loading, setLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [stateOptions, setStateOptions] = useState([]);

  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    date_of_birth: "",
    street_address: "",
    city: "",
    state: "",
    zipcode: "",
    primary_phone: "",   // display formatted
    _primary_phone_raw: "", // raw digits for payload
  });

  useEffect(() => {
    fetchJuror();
    fetchStates();
  }, []);

  const fetchStates = async () => {
  try {
    const res = await getAllStates();
    const options = res.data.data.map((s) => ({  // note: res.data.data because response shape is { status, data: [...] }
      label: s.short_name,
      value: s.id,
    }));
    setStateOptions(options);
  } catch (err) {
    console.error("Failed to load states", err);
  }
};

  const fetchJuror = async () => {
    try {
      setPageLoading(true);
      const res = await getJurorById(id);
      const data = res.data;

      setFormData({
        first_name: data.first_name || "",
        last_name: data.last_name || "",
        date_of_birth: data.date_of_birth || "",
        street_address: data.street_address || "",
        city: data.city || "",
        state: data.state || "",
        zipcode: data.zipcode || "",
        primary_phone: formatUSPhone(data.primary_phone || ""),
        _primary_phone_raw: String(data.primary_phone || "").replace(/\D/g, ""),
      });
    } catch (err) {
      console.error(err);
      toast.error("Failed to load juror");
    } finally {
      setPageLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    let updatedValue = value;

    switch (name) {
      case "first_name":
      case "last_name":
      case "city":
        updatedValue = value.replace(/[^a-zA-Z.\s]/g, "");
        setFormData((prev) => ({ ...prev, [name]: updatedValue }));
        return;

      case "primary_phone": {
        const raw = value.replace(/\D/g, "").slice(0, 10);
        setFormData((prev) => ({
          ...prev,
          primary_phone: formatUSPhone(raw),
          _primary_phone_raw: raw,
        }));
        return;
      }

      case "zipcode":
        updatedValue = value.replace(/\D/g, "").slice(0, 8);
        break;

      case "street_address":
        updatedValue = value.replace(/[^a-zA-Z0-9\s,./-]/g, "");
        break;

      default:
        updatedValue = value;
    }

    setFormData((prev) => ({ ...prev, [name]: updatedValue }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (loading) return;

    try {
      setLoading(true);

      const payload = new FormData();

      const fieldMap = {
        first_name: formData.first_name,
        last_name: formData.last_name,
        date_of_birth: formData.date_of_birth,
        street_address: formData.street_address,
        city: formData.city,
        state: formData.state,
        zipcode: formData.zipcode,
        primary_phone: formData._primary_phone_raw, // send digits only
      };

      Object.entries(fieldMap).forEach(([key, val]) => {
        if (val !== null && val !== undefined && val !== "") {
          payload.append(key, val);
        }
      });

      await updateJuror(id, payload);
      toast.success("Juror updated successfully");
      navigate("/juror-management");
    } catch (err) {
      const message =
        err?.response?.data
          ? Object.values(err.response.data)?.flat()?.[0]
          : "Failed to update juror";
      toast.error(message);
    } finally {
      setLoading(false);
    }
  };

  if (pageLoading) {
    return (
      <Layout title="Edit Juror">
        <div className="text-center p-5">Loading...</div>
      </Layout>
    );
  }

  return (
    <Layout title="Edit Juror">
      <div className="dshboardwhtepnel">
        <div className="pagerlink">
          <ul>
            <li><Link href="/dashboard">Dashboard</Link></li>
            <li><Link href="/juror-management">Juror Management</Link></li>
            <li>Edit Juror</li>
          </ul>
        </div>

        <form className="dshboardcaseform" onSubmit={handleSubmit}>
          <h3>Edit Juror</h3>
          <div className="row">

            {/* First Name */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>First Name</label>
                <input
                  type="text"
                  name="first_name"
                  value={formData.first_name}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* Last Name */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Last Name</label>
                <input
                  type="text"
                  name="last_name"
                  value={formData.last_name}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* Date of Birth */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Date of Birth</label>
                <input
                  type="date"
                  name="date_of_birth"
                  value={formData.date_of_birth}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* Street Address */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Street Address</label>
                <input
                  type="text"
                  name="street_address"
                  value={formData.street_address}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* City */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>City</label>
                <input
                  type="text"
                  name="city"
                  value={formData.city}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* State */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>State</label>
                <CustomSelect
                  name="state"
                  value={formData.state}
                  placeholder="Select State"
                  options={stateOptions}
                  onChange={(e) =>
                    setFormData((prev) => ({ ...prev, state: e.target.value }))
                  }
                />
              </div>
            </div>

            {/* Zipcode */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Zipcode</label>
                <input
                  type="text"
                  name="zipcode"
                  value={formData.zipcode}
                  onChange={handleChange}
                />
              </div>
            </div>

            {/* Phone */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Phone Number</label>
                <input
                  type="text"
                  name="primary_phone"
                  value={formData.primary_phone}
                  onChange={handleChange}
                  placeholder="(555) 555-5555"
                />
              </div>
            </div>

            {/* Buttons */}
            <div className="col-12">
              <div className="datafrmbtn">
                <ul>
                  <li>
                    <button
                      type="button"
                      className="canselbtn"
                      onClick={() => navigate("/juror-management")}
                    >
                      Cancel
                    </button>
                  </li>
                  <li>
                    <button type="submit" disabled={loading}>
                      {loading ? "Updating..." : "Update Juror"}
                    </button>
                  </li>
                </ul>
              </div>
            </div>

          </div>
        </form>
      </div>
    </Layout>
  );
};

export default EditJuror;