import CustomSelect from '@/components/common/CustomSelect';
import { assignCaseAnalyst, assignCaseAttorney, getCaseAnalyst, getCaseAttorney } from '@/services/caseService';
import { createUserWithCase, getAllRole } from '@/services/userService';
import { useParams } from 'next/navigation';
import useNavigate from '@/hooks/useNavigate';
import React, { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { useProfile } from '@/context/ProfileContext';

const AssigningAnalystAttorneyBackup = (caseData) => {
  const { profile } = useProfile();

  const isAnalyst =
    profile?.role_details?.[0]?.name?.includes("Analyst");
  const navigate = useNavigate();

  // Get caseId from URL
  const { id: caseId } = useParams();

  const [loading, setLoading] = useState(false);
  const [roleLoading, setRoleLoading] = useState(true);
  const [roles, setRoles] = useState([]);
  const [analyst, setAnalyst] = useState([]);
  const [attorneys, setAttorneys] = useState([]);
  const [selectedAnalysts, setSelectedAnalysts] = useState([]);
  const [selectedAttorneys, setSelectedAttorneys] = useState([]);

  const canEditStatus =
    !isAnalyst ||
    Number(caseData?.data?.lead_consultant_id) === Number(profile?.id);

  const [formData, setFormData] = useState({
    full_name: "",
    phone_number: "",
    email: "",
    organization_name: "",
    address: "",
    role_id: "",
    password: "",
  });
  const [errors, setErrors] = useState({
    full_name: "",
    email: "",
    phone_number: "",
    password: "",
  });

  useEffect(() => {
    async function fetchRoles() {
      try {
        setRoleLoading(true);

        const res = await getAllRole();

        const formattedRoles = res.data?.map((r) => ({
          value: r.id.toString(),
          label: r.name,
        })) || [];

        setRoles(formattedRoles);
      } catch (err) {
        console.error("Failed to load roles", err);
        toast.error("Failed to load roles");
      } finally {
        setRoleLoading(false);
      }
    }

    fetchRoles();
  }, []);

  const fetchAnalysts = async () => {
    try {
      const response = await getCaseAnalyst(caseId);
      setAnalyst(response?.data?.results || []);
    } catch (error) {
      console.error("Failed to load analysts", error);
    }
  };

  const fetchAttorneys = async () => {
    try {
      const response = await getCaseAttorney(caseId);
      setAttorneys(response?.data?.results || []);
    } catch (error) {
      console.error("Failed to load attorneys", error);
    }
  };

  useEffect(() => {
    if (caseId) {
      fetchAnalysts();
      fetchAttorneys();
    }
  }, [caseId]);

  const handleAnalystCheckboxChange = (id) => {
    setSelectedAnalysts(prev =>
      prev.includes(id)
        ? prev.filter(item => item !== id)
        : [...prev, id]
    );
  };


  const handleAttorneyCheckboxChange = (id) => {
    setSelectedAttorneys(prev =>
      prev.includes(id)
        ? prev.filter(item => item !== id)
        : [...prev, id]
    );
  };


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

  //   if (name === "phone_number") {
  //     const numericValue = value.replace(/\D/g, "").slice(0, 15);

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

  //     return;
  //   }

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

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

    let updatedValue = value;
    if (name === "full_name") {
      updatedValue = value.replace(/[^a-zA-Z\s]/g, "");
    }

    if (name === "phone_number") {
      updatedValue = formatUSPhone(value);
    }

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

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

  const handleRoleChange = (selectedOption) => {

    setFormData((prev) => ({
      ...prev,
      role_id: selectedOption.target.value
    }));
  };

  const toUSPhoneE164 = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    if (digits.length !== 10) return "";

    return `${digits}`;
  };

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

    if (loading) return;

    if (!formData.full_name || !formData.email) {
      toast.warn("Full name and email are required!");
      return;
    }

    try {
      setLoading(true);

      const payload = {
        case_id: Number(caseId),
        email: formData.email,
        password: formData.password,
        roles: [Number(formData.role_id)],

        details: {
          full_name: formData.full_name,
          phone_number: toUSPhoneE164(formData.phone_number),
          organization_name: formData.organization_name,
          address: formData.address,
          status: "available",
        }
      };


      await createUserWithCase(payload);

      toast.success("User created successfully!");
      if (caseId) {
        fetchAnalysts();
        fetchAttorneys();
      }
      // navigate("/user-management");

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

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

        let message = "Failed to create user";

        // ✅ handle nested "details" errors
        if (data.details && typeof data.details === "object") {
          const firstKey = Object.keys(data.details)[0];
          message = data.details[firstKey]?.[0] || message;
        }

        // fallback for normal error formats
        else if (typeof data === "object") {
          const firstValue = Object.values(data)?.[0];

          if (Array.isArray(firstValue)) {
            message = firstValue?.[0];
          } else if (typeof firstValue === "string") {
            message = firstValue;
          }
        }

        toast.error(message);
      } else {
        toast.error("Failed to create user");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleAssignAnalyst = async () => {
    try {
      // if (!selectedAnalysts.length) {
      //   toast.warn("Please select at least one analyst");
      //   return;
      // }

      const payload = {
        user_id: selectedAnalysts,
        case_id: Number(caseId)
      };

      await assignCaseAnalyst(payload);

      toast.success("Analyst assigned successfully");

      setSelectedAnalysts([]);

      await fetchAnalysts();
    } catch (error) {
      console.error(error);
      toast.error("Failed to assign analyst");
    }
  };

  const handleAssignAttorney = async () => {
    try {
      // if (!selectedAttorneys.length) {
      //   toast.warn("Please select at least one attorney");
      //   return;
      // }

      const payload = {
        user_id: selectedAttorneys,
        case_id: Number(caseId)
      };

      await assignCaseAttorney(payload);

      toast.success("Attorney assigned successfully");

      setSelectedAttorneys([]);

      await fetchAttorneys();

    } catch (error) {
      console.error(error);
      toast.error("Failed to assign attorney");
    }
  };

  // const filteredRoles = roles.filter(
  //   (role) =>
  //     !(String(role.value) === "6" && role.label?.trim() === "paralegal")
  // );

  useEffect(() => {
    if (analyst?.length) {
      const preSelected = analyst
        .filter(item => item.assigned === 1)
        .map(item => item.id);

      setSelectedAnalysts(preSelected);
    }
  }, [analyst]);

  useEffect(() => {
    if (attorneys?.length) {
      const preSelected = attorneys
        .filter(item => item.assigned === 1)
        .map(item => item.id);

      setSelectedAttorneys(preSelected);
    }
  }, [attorneys]);

  const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    if (digits.length === 0) return "";
    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 validateField = (name, value) => {
    let error = "";

    if (name === "full_name") {
      if (!value || value.trim().length < 2) {
        error = "Full name must be at least 2 characters";
      }
    }

    if (name === "email") {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!value || !emailRegex.test(value)) {
        error = "Enter a valid email address";
      }
    }

    if (name === "phone_number") {
      if (value) {
        const digitsOnly = value.replace(/\D/g, "");
        const phoneRegex = /^[0-9]{10,11}$/;

        if (!phoneRegex.test(digitsOnly)) {
          error = "Enter valid US phone number";
        }
      }
    }

    if (name === "password") {
      if (!value) {
        error = "Password is required";
      } else if (
        !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?#&^()_\-+=])[A-Za-z\d@$!%*?#&^()_\-+=]{8,}$/.test(value)
      ) {
        error =
          "Minimum 8 chars with uppercase, lowercase, number & special character";
      }
    }

    return error;
  };

  return (
    <>
      {canEditStatus && (
        <div className="dshboardwhtepnel">
          <form className="dshboardcaseform" onSubmit={handleSubmit}>
            <h3>Add new Analyst / Attorney / Paralegal</h3>
            <div className="row">
              {/* Full Name */}
              <div className="col-lg-4 col-sm-6">
                <div className="datafrm">
                  <label>Full Name <span className="text-danger" >*</span></label>
                  <input
                    type="text"
                    name="full_name"
                    value={formData.full_name}
                    onChange={handleChange}
                    placeholder="Enter full name"
                    required
                  />

                  {errors.full_name && (
                    <small className="text-danger">{errors.full_name}</small>
                  )}
                </div>
              </div>

              {/* Phone Number */}
              <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"
                  />
                  {errors.phone_number && (
                    <small className="text-danger">{errors.phone_number}</small>
                  )}
                </div>
              </div>

              {/* Email */}
              <div className="col-lg-4 col-sm-6">
                <div className="datafrm">
                  <label>E-mail Address <span className="text-danger" >*</span></label>
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    placeholder="Enter e-mail address"
                    required
                  />
                  {errors.email && (
                    <small className="text-danger">{errors.email}</small>
                  )}
                </div>
              </div>

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

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

              {/* User Role */}
              <div className="col-lg-4 col-sm-6">
                <div className="datafrm">
                  <label>Select User Role</label>

                  {roleLoading ? (
                    <p>Loading roles...</p>
                  ) : (
                    <CustomSelect
                      name="role_id"
                      value={formData.role_id}
                      onChange={handleRoleChange}
                      placeholder="Select user role"
                      options={roles}
                    />
                  )}
                </div>
              </div>

              {/* Password */}
              <div className="col-lg-4 col-sm-6">
                <div className="datafrm">
                  <label>Password <span className="text-danger" >*</span></label>
                  <input
                    type="password"
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    placeholder="Enter password"
                    required
                  />
                  {errors.password && (
                    <small className="text-danger">{errors.password}</small>
                  )}
                </div>
              </div>

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

            </div>
          </form>
        </div>)}

      <div className="row">

        {/* Analyst */}
        <div className="col-xl-6 col-lg-6 col-sm-12 col-12 mt-3 mt-md-4">
          <div className="casetabnx">
            {/* <div className="indicationbtx">
              <div className="indicationbtx">
                <span>Analyst</span>
                <em style={{background: "#b3d9ff",}}></em>
              </div>
              <div className="indicationbtx">
                <span>Attorney</span>
                <em style={{background: "#A17D3A",}}></em>
              </div>
            </div> */}
            <div className="d-flex justify-content-between gap-2 mb-2 mb-md-3">
              <div className="w-100">
                <h4>Available Analyst ({analyst?.length || 0})</h4>
                <p>Select analysts from the available pool to add to this case.</p>
              </div>
            </div>

            <div className="importedlistouter">

              {analyst?.map((item) => (
                <div className="importedlist" key={item.id}>

                  <div className="form-check">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      disabled={item.status == "busy"}
                      checked={selectedAnalysts.includes(item.id)}
                      onChange={() => handleAnalystCheckboxChange(item.id)}
                    />
                  </div>

                  <div className="importedmediabx">

                    <div className="importedmedia">
                      {item?.name
                        ?.split(" ")
                        ?.map(word => word[0])
                        ?.join("")
                        ?.substring(0, 2)}
                    </div>

                    <div className="importedmediact">
                      <h5>{item.name}</h5>
                      <p className='mb-1'>{item.organization_name || "No Organization"}</p>
                      {/* <p>{item.address || "No Address"}</p> */}
                      <p className='mb-1'>{item.phone_number || "No Phone"}</p>
                      <p className='mb-1 text-capitalize'>{item.status}</p>
                    </div>

                  </div>

                  {item.assigned === 1 && (
                    <span className="assign-badge">Already Assigned</span>
                  )}

                </div>
              ))}

            </div>

            {canEditStatus && (
              <div className="text-end">
                <button
                  className="adduser d-inline-flex gap-2 mt-3"
                  type="button"
                  onClick={handleAssignAnalyst}
                >
                  <span>Assign Analyst</span>
                </button>
              </div>)}

          </div>
        </div>


        {/* Attorney */}
        <div className="col-xl-6 col-lg-6 col-sm-12 col-12 mt-3 mt-md-4">
          <div className="casetabnx">
            <div className="indicationbtx">
              <div className="indicationbtx">
                <em style={{ background: "#e3f1ff", border: "1px solid #c3e1ff"}}></em>
                <span>Paralegal</span>
              </div>
              <div className="indicationbtx">
                <em style={{ background: "#fdf6ea", border: "1px solid #efe3ce" }}></em>
                <span>Attorney</span>
              </div>
            </div>
            <div className="d-flex justify-content-between gap-2 mb-2 mb-md-3">
              <div className="w-100">
                <h4>Available Attorney / Paralegal ({attorneys?.length || 0})</h4>
                <p>Select attorneys from the available pool to add to this case.</p>
              </div>
            </div>

            <div className="importedlistouter">

              {attorneys?.map((item) => (
                <div className={`importedlist ${item.role_name == "Attorney" ? 'attorney' : 'para-legal'}`} style={{ background: item.role_name == "Attorney" ? "" : "", }} key={item.id}>

                  <div className="form-check">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      disabled={item.status == "busy"}
                      checked={selectedAttorneys.includes(item.id)}
                      onChange={() => handleAttorneyCheckboxChange(item.id)}
                    />
                  </div>

                  <div className="importedmediabx">

                    <div className="importedmedia">
                      {item?.name
                        ?.split(" ")
                        ?.map(word => word[0])
                        ?.join("")
                        ?.substring(0, 2)}
                    </div>

                    <div className="importedmediact">
                      <h5>{item.name}</h5>
                      <p className='mb-1'>{item.organization_name || "No Organization"}</p>
                      {/* <p>{item.address || "No Address"}</p> */}
                      <p className='mb-1'>{item.phone_number || "No Phone"}</p>
                      <p className='mb-1 text-capitalize'>{item.status}</p>
                    </div>

                  </div>

                  <div className="importedlistbtm">

                  </div>

                  {item.assigned === 1 && (
                    <span className="assign-badge">
                      Already Assigned
                    </span>
                  )}

                </div>
              ))}

            </div>

            {canEditStatus && (
              <div className="text-end">
                <button
                  className="adduser d-inline-flex gap-2 mt-3"
                  type="button"
                  onClick={handleAssignAttorney}
                >
                  <span>Assign Attorney</span>
                </button>
              </div>)}

          </div>
        </div>

      </div>
    </>
  )
}

export default AssigningAnalystAttorneyBackup