import React, { useState, useEffect } from "react";
import CustomSelect from "../../../common/CustomSelect";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import {
  getLeadAttorneys,
  getLeadConsultants,
  getJurisdiction,
  getCourtSystem,
} from "@/services/caseService";
import { toast } from "react-toastify";
import { useProfile } from "@/context/ProfileContext";
import { getAllStates } from "@/services/jurorsService";
export default function ViewCaseInfo({ data, onUpdate }) {
  const { profile } = useProfile();

  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const [formData, setFormData] = useState({});
  const [changedFields, setChangedFields] = useState({});
  const [courtSystems, setCourtSystems] = useState([]);
  const [leadAttorneys, setLeadAttorneys] = useState([]);
  const [leadConsultants, setLeadConsultants] = useState([]);
  const [jurisdictions, setJurisdictions] = useState([]);
  const [dropdownLoading, setDropdownLoading] = useState(true);
  const [stateOptions, setStateOptions] = useState([]);

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

  useEffect(() => {
    const fetchDropdownData = async () => {
      try {
        setDropdownLoading(true);

        const [attorneysRes, consultantsRes] = await Promise.all([
          getLeadAttorneys(),
          getLeadConsultants(),
        ]);

        setLeadAttorneys(attorneysRes.data || []);
        setLeadConsultants(consultantsRes.data || []);
      } catch (err) {
        console.error("Error loading dropdown data:", err);
        toast.error("Failed to load lead attorneys and consultants");
      } finally {
        setDropdownLoading(false);
      }
    };

    fetchDropdownData();
  }, []);

  // Set initial form data
  useEffect(() => {
    setFormData({
      ...data,
      start_date_of_jury_selection: data?.start_date_of_jury_selection
        ? new Date(data.start_date_of_jury_selection)
        : null,
      deadline: data?.deadline ? new Date(data.deadline) : null,
    });
    setChangedFields({});
  }, [data]);

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

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

  const validateForm = () => {
    const requiredFields = [
      "name",
      "case_id",
      "court_name",
      "jurisdiction",
      "court_type",
      "state",
      "lead_attorney_id",
      "lead_consultant_id",
      "case_status",
    ];

    const fieldMessages = {
      name: "Please enter Case Name",
      case_id: "Please enter Case ID",
      court_name: "Please enter Court Name",
      court_type: "Please select Court Type",
      state: "Please select State",
      jurisdiction: "Please select Jurisdiction",
      lead_attorney_id: "Please select Lead Attorney",
      lead_consultant_id: "Please select Lead Analyst",
      case_status: "Please select Status",
    };

    for (const field of requiredFields) {
      const value = formData[field];

      if (
        value === null ||
        value === undefined ||
        value === "" ||
        (typeof value === "string" && value.trim() === "")
      ) {
        toast.error(fieldMessages[field]);
        return false;
      }
    }

    return true;
  };

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

    if (!validateForm()) return;

    const payload = {
      ...changedFields,
      priority: changedFields.priority
        ? changedFields.priority.toLowerCase().trim()
        : changedFields.priority,
    };
    console.log(payload);
    onUpdate(payload);
  };

  const handleCancel = () => {
    setFormData({
      ...data,
      start_date_of_jury_selection: data?.start_date_of_jury_selection
        ? new Date(data.start_date_of_jury_selection)
        : null,
      deadline: data?.deadline ? new Date(data.deadline) : null,
    });
    setChangedFields({});
  };

  const fetchStates = async () => {
    try {
      const response = await getAllStates();
      const options = (response?.data?.data || []).map((item) => ({
        label: item.short_name,
        value: item.id,
      }));
      setStateOptions(options);
    } catch (error) {}
  };

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

  const courtTypeOptions = [
    {
      label: "Federal",
      options: [
        { value: "USSC", label: "USSC" },
        { value: "US District", label: "US District" },
        { value: "US Bankruptcy", label: "US Bankruptcy" },
        { value: "US Tax", label: "US Tax" },
        { value: "Federal Other", label: "Other" },
      ],
    },
    {
      label: "State / Federal / Special / Other",
      options: [
        { value: "State Supreme", label: "State Supreme" },
        { value: "State Appellate", label: "State Appellate" },
        { value: "State Trial", label: "State Trial" },
        { value: "Family Court", label: "Family Court" },
        { value: "Juvenile", label: "Juvenile " },
        { value: "Traffic ", label: "Traffic " },
        { value: "Probate", label: "Probate" },
      ],
    },
  ];

  return (
    <div>
      <form className="dshboardcaseform" onSubmit={handleSubmit}>
        <div className="d-block justify-content-between mt-3 ">
          <h3>Case Details</h3>
          <p>
            Admin-only: Core case information that can only be modified by
            administrators.
          </p>
        </div>

        <div className="row gx-2">
          {/* Case Name */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Case Name <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                name="name"
                value={formData.name || ""}
                onChange={handleChange}
              />
            </div>
          </div>

          {/* Case ID */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Case ID <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                name="case_id"
                value={formData.case_id || ""}
                onChange={handleChange}
              />
            </div>
          </div>

          {/* Case Type */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>Case Type</label>

              <CustomSelect
                name="case_type"
                value={formData.case_type || ""}
                onChange={handleChange}
                placeholder="Select Case Type"
                options={[
                  { value: "Criminal", label: "Criminal" },
                  { value: "Civil", label: "Civil" },
                  { value: "Other", label: "Other" },
                ]}
              />
            </div>
          </div>

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

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

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

          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                State <span className="text-danger">*</span>
              </label>

              <CustomSelect
                name="state"
                value={formData.state || ""}
                placeholder="Select State"
                options={stateOptions}
                onChange={handleChange}
              />
            </div>
          </div>

          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Jurisdiction <span className="text-danger">*</span>
              </label>
              <CustomSelect
                name="jurisdiction"
                value={formData.jurisdiction}
                onChange={handleChange}
                placeholder="Select Jurisdiction"
                options={[
                  { value: "County", label: "County" },
                  { value: "State", label: "State" },
                  { value: "Federal", label: "Federal" },
                  { value: "Special", label: "Special" },
                  { value: "Other", label: "Other" },
                ]}
              />
            </div>
          </div>

          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Court Type <span className="text-danger">*</span>
              </label>

              <CustomSelect
                name="court_type"
                value={formData.court_type || ""}
                onChange={handleChange}
                placeholder="Select Court Type"
                options={courtTypeOptions}
                isGrouped={true}
              />
            </div>
          </div>

          {/* Judge */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Judge <span className="text-danger">*</span>
              </label>
              <input
                type="text"
                name="judge_name"
                value={formData.judge_name || ""}
                onChange={handleChange}
              />
            </div>
          </div>

          {/* Lead Attorney */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Lead Attorney <span className="text-danger">*</span>
              </label>

              {isAnalyst ? (
                <input
                  type="text"
                  className="form-control"
                  value={
                    leadAttorneys.find(
                      (item) => item.id === formData.lead_attorney_id,
                    )?.details?.full_name || ""
                  }
                  readOnly
                />
              ) : (
                <CustomSelect
                  name="lead_attorney_id"
                  value={formData.lead_attorney_id}
                  onChange={handleChange}
                  options={leadAttorneys.map((item) => ({
                    value: item.id,
                    label: item.details.full_name,
                  }))}
                  isLoading={dropdownLoading}
                />
              )}
            </div>
          </div>

          {/* Lead Consultant */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Lead Analyst <span className="text-danger">*</span>
              </label>

              {isAnalyst ? (
                <input
                  type="text"
                  className="form-control"
                  value={
                    leadConsultants.find(
                      (item) => item.id === formData.lead_consultant_id,
                    )?.details?.full_name || ""
                  }
                  readOnly
                />
              ) : (
                <CustomSelect
                  name="lead_consultant_id"
                  value={formData.lead_consultant_id}
                  onChange={handleChange}
                  options={leadConsultants.map((item) => ({
                    value: item.id,
                    label: item.details.full_name,
                  }))}
                  isLoading={dropdownLoading}
                />
              )}
            </div>
          </div>

          {/* Start Date */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>Start Date of Jury Selection</label>
              <div className="datafrminner">
                <svg
                  width="16"
                  height="18"
                  viewBox="0 0 16 18"
                  className="form-icon"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z"
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
                <DatePicker
                  dateFormat="MM-dd-yyyy"
                  placeholderText="MM-DD-YYYY"
                  className="form-control"
                  selected={formData.start_date_of_jury_selection}
                  onChange={(value) =>
                    handleDateChange("start_date_of_jury_selection", value)
                  }
                />
              </div>
            </div>
          </div>

          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>Priority</label>

              <CustomSelect
                name="priority"
                value={formData.priority || ""}
                onChange={handleChange}
                placeholder="Select Priority"
                options={[
                  { value: "low", label: "Low" },
                  { value: "medium", label: "Medium" },
                  { value: "high", label: "High" },
                ]}
              />
            </div>
          </div>

          {/* Deadline */}
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>Deadline</label>
              <div className="datafrminner">
                <svg
                  width="16"
                  height="18"
                  viewBox="0 0 16 18"
                  className="form-icon"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M4.62139 0.5V2.97412M11.2156 0.5V2.97412M0.912139 6.34725H14.9249M10.964 10.149H10.9714M10.964 12.6232H10.9714M7.91478 10.149H7.92218M7.91478 12.6232H7.92218M4.86398 10.149H4.87139M4.86398 12.6232H4.87139M15.337 5.8606V12.8706C15.337 15.3447 14.1006 16.9941 11.2156 16.9941H4.62139C1.73642 16.9941 0.5 15.3447 0.5 12.8706V5.8606C0.5 3.38647 1.73642 1.73706 4.62139 1.73706H11.2156C14.1006 1.73706 15.337 3.38647 15.337 5.8606Z"
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
                <DatePicker
                  dateFormat="MM-dd-yyyy"
                  placeholderText="MM-DD-YYYY"
                  className="form-control"
                  selected={formData.deadline}
                  onChange={(value) => handleDateChange("deadline", value)}
                />
              </div>
            </div>
          </div>

          {/* Case Description */}
          <div className="col-12">
            <div className="datafrm">
              <label>Case Description</label>
              <textarea
                name="case_desc"
                value={formData.case_desc || ""}
                onChange={handleChange}
              ></textarea>
            </div>
          </div>

          {/* Key Phases */}
          <div className="col-12">
            <div className="datafrm">
              <label>Key Phrases for Ideal Juror</label>
              <textarea
                type="text"
                name="key_phases_for_ideal_juror"
                value={formData.key_phases_for_ideal_juror || ""}
                onChange={handleChange}
              ></textarea>
            </div>
          </div>

          <div className="col-12">
            <div className="datafrm">
              <label>Key Phrases for Warning Sign</label>
              <textarea
                type="text"
                name="key_phases_for_warn_sign"
                value={formData.key_phases_for_warn_sign || ""}
                onChange={handleChange}
              ></textarea>
            </div>
          </div>
          <div className="col-lg-4 col-sm-6">
            <div className="datafrm">
              <label>
                Status <span className="text-danger">*</span>
              </label>

              {isAnalyst &&
              Number(data?.lead_consultant_id) !== Number(profile?.id) ? (
                <input
                  type="text"
                  className="form-control"
                  value={
                    formData.case_status
                      ? formData.case_status.charAt(0).toUpperCase() +
                        formData.case_status.slice(1)
                      : ""
                  }
                  readOnly
                />
              ) : (
                <CustomSelect
                  name="case_status"
                  value={formData.case_status || ""}
                  onChange={handleChange}
                  options={[
                    { value: "waiting", label: "Waiting" },
                    { value: "active", label: "Active" },
                    { value: "inactive", label: "Inactive" },
                    { value: "archived", label: "Archived" },
                  ]}
                />
              )}
            </div>
          </div>

          {canEditStatus && (
            <div className="col-12">
              <div className="datafrmbtn d-flex gap-2 justify-content-end">
                <button
                  type="button"
                  className="canselbtn"
                  onClick={handleCancel}
                >
                  Cancel
                </button>
                <button className="d-inline-flex gap-2" type="submit">
                  <svg
                    width="13"
                    height="16"
                    viewBox="0 0 13 16"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M7.75016 0.75V3.55006C7.75016 3.92138 7.89767 4.27748 8.16022 4.54004C8.42278 4.80259 8.77888 4.9501 9.15019 4.9501H11.9503M4.9501 5.65011H3.55006M9.15019 8.45018H3.55006M9.15019 11.2502H3.55006M8.45018 0.75H2.15003C1.77872 0.75 1.42262 0.897503 1.16006 1.16006C0.897503 1.42262 0.75 1.77872 0.75 2.15003V13.3503C0.75 13.7216 0.897503 14.0777 1.16006 14.3403C1.42262 14.6028 1.77872 14.7503 2.15003 14.7503H10.5502C10.9215 14.7503 11.2776 14.6028 11.5402 14.3403C11.8028 14.0777 11.9503 13.7216 11.9503 13.3503V4.25008L8.45018 0.75Z"
                      stroke="white"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                  <span>Save Changes</span>
                </button>
              </div>
            </div>
          )}
        </div>
      </form>
    </div>
  );
}
