import React, { useState } from "react";
import { toast } from "react-toastify";
import useNavigate from '@/hooks/useNavigate';
import Layout from "@/Layout";
import { createJurors } from "@/services/jurorsService";
import Link from "next/link";

export default function AddJuror() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    birth_date: "",
    max_age: "",
    current_address: "",
    current_city: "",
    current_state: "",
    country: "",
    zipcode: "",
    phone_number: "",
    profile_picture: null,
  });

  // const handleChange = (e) => {
  //   const { name, value, files } = e.target;

  //   setFormData((prev) => ({
  //     ...prev,
  //     [name]: files ? files[0] : value,
  //   }));
  // };

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

    if (files) {
      setFormData((prev) => ({
        ...prev,
        [name]: files[0],
      }));
      return;
    }

    let updatedValue = value;

    switch (name) {
      case "first_name":
      case "last_name":
      case "current_city":
      case "current_state":
      case "country":
        updatedValue = value.replace(/[^a-zA-Z.\s]/g, "");
        break;

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

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

      case "current_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);

      // Create FormData object
      const payload = new FormData();

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

      await createJurors(payload);

      toast.success("Juror created successfully!");
      navigate("/juror-management");

    } catch (err) {
      console.error("Juror creation failed:", err);

      if (err.response?.data) {
        const errors = err.response.data;

        const firstMessage =
          Object.values(errors)?.flat()?.[0];

        toast.error(firstMessage || "Failed to create juror");
      } else {
        toast.error("Failed to create juror");
      }

    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout title="Add New 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>Add new juror</li>
          </ul>
        </div>

        <form className="dshboardcaseform" onSubmit={handleSubmit}>
          <h3>Add new 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}
                  placeholder="Enter first name"
                  required
                />
              </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}
                  placeholder="Enter last name"
                  required
                />
              </div>
            </div>

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

            {/* Max Age */}
            {/* <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Max Age (&gt;18)*</label>
                <input
                  type="number"
                  name="max_age"
                  value={formData.max_age}
                  onChange={handleChange}
                  min="18"
                  placeholder="Enter max age"
                  required
                />
              </div>
            </div>  */}

            {/* Address */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Current Address*</label>
                <input
                  type="text"
                  name="current_address"
                  value={formData.current_address}
                  onChange={handleChange}
                  placeholder="Enter address"
                  required
                />
              </div>
            </div>

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

            {/* State */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Current State*</label>
                <input
                  type="text"
                  name="current_state"
                  value={formData.current_state}
                  onChange={handleChange}
                  placeholder="Enter state"
                  required
                />
              </div>
            </div>

            {/* Country */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Country*</label>
                <input
                  type="text"
                  name="country"
                  value={formData.country}
                  onChange={handleChange}
                  placeholder="Enter country"
                  required
                />
              </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}
                  placeholder="Enter zipcode"
                  required
                />
              </div>
            </div>

            {/* Phone */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Phone Number</label>
                <input
                  type="tel"
                  name="phone_number"
                  value={formData.phone_number}
                  onChange={handleChange}
                  placeholder="Enter phone number"
                />
              </div>
            </div>

            {/* Profile Image */}
            {/* <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Profile Picture</label>
                <input
                  type="file"
                  name="profile_picture"
                  accept="image/*"
                  onChange={handleChange}
                />
              </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 ? "Creating..." : "Create Juror"}
                    </button>
                  </li>
                </ul>
              </div>
            </div>

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