import React, { useState, useRef, useEffect } from "react";
import Layout from "../../Layout";
import {
  createCase,
  getLeadAttorneys,
  getLeadConsultants,
  getJurisdiction,
  getCourtSystem,
} from "@/services/caseService";
import { toast } from "react-toastify";
import useNavigate from "@/hooks/useNavigate";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { format, isValid } from "date-fns";
import CustomSelect from "../../components/common/CustomSelect";
import UploadModal from "../../components/common/UploadModal";
import Link from "next/link";
import { getAllStates } from "@/services/jurorsService";

  const ALLOWED_EXTENSIONS = [
    "pdf",
    "doc",
    "docx",
    "txt",
    "jpg",
    "jpeg",
    "png",
  ];

export default function CreateNewCase() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const fileInputRef = useRef(null);

  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [tempSelectedFiles, setTempSelectedFiles] = useState([]);
  const [stateOptions, setStateOptions] = useState([]);

  const [leadAttorneys, setLeadAttorneys] = useState([]);
  const [leadConsultants, setLeadConsultants] = useState([]);
  const [courtSystems, setCourtSystems] = useState([]);
  const [jurisdictions, setJurisdictions] = useState([]);
  const [errors, setErrors] = useState({});

  const [dropdownLoading, setDropdownLoading] = useState(true);

  const [formData, setFormData] = useState({
    name: "",
    case_id: "",
    court_system: "",
    court_name: "",
    judge_name: "",
    jurisdiction: "",

    city: "",
    county: "",
    state: "",
    court_type: "",

    lead_attorney_id: "",
    lead_consultant_id: "",
    start_date_of_jury_selection: "",
    priority: "",
    case_type: "",
    deadline: "",
    case_desc: "",
    key_phases_for_ideal_juror: "",
    key_phases_for_warn_sign: "",
    case_status: "",
  });

  const [uploadFiles, setUploadFiles] = useState([]);

  // Fetch lead attorneys & consultants on mount
  // useEffect(() => {
  //   const fetchDropdownData = async () => {
  //     try {
  //       setDropdownLoading(true);
  //       const [attorneysRes, consultantsRes, jurisdictionRes, courtSystemRes] = await Promise.all([
  //         getLeadAttorneys(),
  //         getLeadConsultants(),
  //         getJurisdiction(),
  //         getCourtSystem()
  //       ]);
  //       setLeadAttorneys(attorneysRes.data || []);
  //       setLeadConsultants(consultantsRes.data || []);
  //       setCourtSystems(courtSystemRes.data || []);
  //       setJurisdictions(jurisdictionRes.data || []);
  //     } catch (err) {
  //       console.error("Error loading dropdown data:", err);
  //       toast.error("Failed to load lead attorneys/consultants/court-sysem/jurisdiction");
  //     } finally {
  //       setDropdownLoading(false);
  //     }
  //   };
  //   fetchDropdownData();
  // }, []);

  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();
  }, []);

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

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

    if (name === "judge_name") {
      const regex = /^[A-Za-z\s]*$/;

      if (!regex.test(value)) {
        setErrors((prev) => ({
          ...prev,
          judge_name: "Only letters are allowed",
        }));
        return;
      } else {
        setErrors((prev) => ({
          ...prev,
          judge_name: "",
        }));
      }
    }

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

  const handleFileChange = (e) => setUploadFiles(e.target.files);
  const handleFileButtonClick = () => fileInputRef.current.click();

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

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

  //     if (
  //       value === null ||
  //       value === undefined ||
  //       value === "" ||
  //       (typeof value === "string" && value.trim() === "")
  //     ) {
  //       toast.error(
  //         `Please fill out the required field: ${field.replace(/_/g, " ")}`,
  //       );
  //       return false;
  //     }
  //   }
  //   return true;
  // };

  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 = async (e) => {
    e.preventDefault();
    if (loading) return;
    if (!validateForm()) return;

    setLoading(true);
    try {
      // Utility: format date as DD-MM-YYYY
      const formatDateToDDMMYYYY = (date) => {
        if (!date) return "";
        const d = new Date(date);
        if (isNaN(d)) return "";
        const day = String(d.getDate()).padStart(2, "0");
        const month = String(d.getMonth() + 1).padStart(2, "0");
        const year = d.getFullYear();
        return `${day}-${month}-${year}`;
      };

      const payload = new FormData();
      // Object.entries(formData).forEach(([key, value]) => {
      //   if (key === "start_date_of_jury_selection" || key === "deadline") {
      //     payload.append(key, formatDateToDDMMYYYY(value));
      //   } else {
      //     payload.append(key, value);
      //   }
      // });

      Object.entries(formData).forEach(([key, value]) => {
        if (key === "start_date_of_jury_selection" || key === "deadline") {
          payload.append(key, formatDateToDDMMYYYY(value));
        } else if (key === "priority") {
          payload.append(key, value?.trim().toLowerCase());
        } else {
          payload.append(key, value);
        }
      });

      const invalidFiles = uploadFiles.filter((file) => {
        const extension = file.name.split(".").pop()?.toLowerCase();
        return !ALLOWED_EXTENSIONS.includes(extension);
      });

      if (invalidFiles.length) {
        toast.error(
          `Only PDF, DOC, DOCX, TXT, JPG, JPEG and PNG files are allowed.\n\nInvalid file(s): ${invalidFiles
            .map((f) => f.name)
            .join(", ")}`
        );
        setLoading(false);
        return;
      }

      if (uploadFiles.length) {
        for (let file of uploadFiles) payload.append("upload_files", file);
      }

      const res = await createCase(payload);
      toast.success("Case created successfully!");

      const createdCaseId = res?.data?.id;
      // navigate("/case-list");
      navigate(`/case-list/edit-case/${createdCaseId}`);

      // Reset form
      setFormData({
        name: "",
        case_id: "",
        court_system: "",
        court_name: "",
        judge_name: "",
        jurisdiction: "",
        city: "",
        county: "",
        state: "",
        court_type: "",
        lead_attorney_id: "",
        lead_consultant_id: "",
        start_date_of_jury_selection: "",
        priority: "",
        case_type: "",
        deadline: "",
        case_desc: "",
        key_phases_for_ideal_juror: "",
        key_phases_for_warn_sign: "",
      });
      setUploadFiles([]);
    } catch (err) {
      console.error(err);

      const errorData = err.response?.data;

      if (errorData && typeof errorData === "object") {
        Object.keys(errorData).forEach((field) => {
          const fieldErrors = errorData[field];

          if (Array.isArray(fieldErrors)) {
            fieldErrors.forEach((msg) => {
              toast.error(msg);
            });
          } else {
            toast.error(fieldErrors);
          }
        });
      } else {
        toast.error(errorData?.message || "Failed to create case");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleModalFileSelect = (e) => {
    const files = Array.from(e.target.files || []);

    const validFiles = [];
    const invalidFiles = [];

    files.forEach((file) => {
      const extension = file.name.split(".").pop()?.toLowerCase();

      if (ALLOWED_EXTENSIONS.includes(extension)) {
        validFiles.push(file);
      } else {
        invalidFiles.push(file.name);
      }
    });

    if (invalidFiles.length) {
      toast.error(
        `Only PDF, DOC, DOCX, TXT, JPG, JPEG and PNG files are allowed.`
      );
    }

    setTempSelectedFiles(validFiles);

    e.target.value = "";
  };

  const handleModalUpload = () => {
    if (!tempSelectedFiles.length) {
      toast.warning("Please select at least one valid file.");
      return;
    }

    setUploadFiles((prev) => [...prev, ...tempSelectedFiles]);

    toast.success(
      `${tempSelectedFiles.length} document${tempSelectedFiles.length > 1 ? "s" : ""
      } attached successfully.`
    );

    setTempSelectedFiles([]);
    setIsUploadModalOpen(false);
  };

  const onRemoveFile = (index) => {
    setUploadFiles((prev) => prev.filter((_, i) => i !== index));
  };

  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" },
        // { value: "State Other", label: "Other" },
      ],
    },
  ];

  return (
    <Layout title="Create New Case">
      <div className="dshboardwhtepnel">
        <div className="pagerlink">
          <ul>
            <li>
              <Link href="/dashboard">Dashboard</Link>
            </li>
            <li>Create New Case</li>
          </ul>
        </div>

        <form className="dshboardcaseform" onSubmit={handleSubmit}>
          <div className="d-flex justify-content-between ">
            <h3>Add a new case</h3>
            <div className="datafrmbtn custom-file-upload m-0">
              <button
                type="button"
                className="upload-btn"
                onClick={() => setIsUploadModalOpen(true)}
              >
                <svg
                  width="21"
                  height="18"
                  viewBox="0 0 21 18"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M10.14 7.32321V12.9572M7.32303 10.1402H12.957M17.6519 16.7129C18.1499 16.7129 18.6276 16.515 18.9798 16.1628C19.332 15.8106 19.5299 15.333 19.5299 14.8349V5.44496C19.5299 4.94689 19.332 4.46922 18.9798 4.11703C18.6276 3.76484 18.1499 3.56698 17.6519 3.56698H10.2338C9.91975 3.57006 9.60991 3.49431 9.33268 3.34667C9.05544 3.19903 8.81967 2.98422 8.64693 2.72189L7.88635 1.59509C7.71535 1.33543 7.48256 1.12229 7.20886 0.974791C6.93517 0.827292 6.62914 0.750051 6.31823 0.75H2.62799C2.12991 0.75 1.65224 0.947859 1.30005 1.30005C0.947859 1.65224 0.75 2.12991 0.75 2.62799V14.8349C0.75 15.333 0.947859 15.8106 1.30005 16.1628C1.65224 16.515 2.12991 16.7129 2.62799 16.7129H17.6519Z"
                    stroke="white"
                    stroke-width="1.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
                Upload Documents
              </button>
              <input
                type="file"
                ref={fileInputRef}
                multiple
                accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png"
                onChange={handleFileChange}
                style={{ display: "none" }}
              />
            </div>
          </div>

          <div className="row">
            {/* Required Fields */}
            <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}
                  placeholder="Enter case name"
                />
              </div>
            </div>

            <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}
                  placeholder="Enter case id"
                />
              </div>
            </div>

            <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>

            {/* <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: "1", label: "Option 1" },
                    { value: "2", label: "Option 2" },
                  ]}
                />
              </div>
            </div> */}

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="court_system"
                    value={formData.court_system}
                    onChange={handleChange}
                    placeholder="Select court system"
                    options={courtSystems.map((item) => ({
                      value: item.id,
                      label: item.name,
                    }))}
                  />
                )}
              </div>
            </div> */}

            {/* Client asked to remove */}
            {/* <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>
                  Court System <span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  name="court_system"
                  value={formData.court_system}
                  onChange={handleChange}
                  placeholder="Enter court system"
                />
              </div>
            </div> */}

            <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}
                  placeholder="Name of the court"
                />
              </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={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      state: e.target.value,
                    }))
                  }
                />
              </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>

            {/* Optional Fields */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Judge </label>
                <input
                  type="text"
                  name="judge_name"
                  value={formData.judge_name}
                  onChange={handleChange}
                  placeholder="Enter judge name"
                />
                {errors.judge_name && (
                  <small style={{ color: "red" }}>{errors.judge_name}</small>
                )}
              </div>
            </div>

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="jurisdiction"
                    value={formData.jurisdiction}
                    onChange={handleChange}
                    placeholder="Select jurisdiction"
                    options={jurisdictions.map((item) => ({
                      value: item.id,
                      label: item.name,
                    }))}
                  />
                )}
              </div>
            </div> */}

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

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="lead_attorney_id"
                    value={formData.lead_attorney_id}
                    onChange={handleChange}
                    placeholder="Select lead attorney"
                    options={leadAttorneys.map((att) => ({
                      value: att.id,
                      label: att.details.full_name || `Attorney #${att.id}`,
                    }))}
                  />
                )}
              </div>
            </div> */}

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="lead_consultant_id"
                    value={formData.lead_consultant_id}
                    onChange={handleChange}
                    placeholder="Select lead consultant"
                    options={leadConsultants.map((con) => ({
                      value: con.id,
                      label: con.details.full_name || `Consultant #${con.id}`,
                    }))}
                  />
                )}
              </div>
            </div> */}

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="lead_attorney_id"
                    value={formData.lead_attorney_id}
                    onChange={handleChange}
                    placeholder="Select lead attorney"
                    options={leadAttorneys.map((att) => ({
                      value: att.id,
                      label: att.details?.full_name || `Attorney #${att.id}`,
                    }))}
                  />
                )}
              </div>
            </div>

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

                {dropdownLoading ? (
                  <p>Loading...</p>
                ) : (
                  <CustomSelect
                    name="lead_consultant_id"
                    value={formData.lead_consultant_id}
                    onChange={handleChange}
                    placeholder="Select lead analyst"
                    options={leadConsultants.map((con) => ({
                      value: con.id,
                      label: con.details?.full_name || `Consultant #${con.id}`,
                    }))}
                  />
                )}
              </div>
            </div>

            {/* Dates */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Start Date of Jury Selection</label>
                <DatePicker
                  selected={formData.start_date_of_jury_selection}
                  onChange={(date) =>
                    setFormData((prev) => ({
                      ...prev,
                      start_date_of_jury_selection: date,
                    }))
                  }
                  dateFormat="MM-dd-yyyy"
                  placeholderText="MM-DD-YYYY"
                  className="form-control"
                  minDate={new Date()}
                />
              </div>
            </div>

            {/* <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Priority</label>
                <input
                  type="text"
                  name="priority"
                  value={formData.priority}
                  onChange={handleChange}
                  placeholder="Enter priority (low, medium, high)"
                />
              </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>

            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Deadline</label>
                <DatePicker
                  selected={formData.deadline}
                  onChange={(date) =>
                    setFormData((prev) => ({
                      ...prev,
                      deadline: date,
                    }))
                  }
                  dateFormat="MM-dd-yyyy"
                  placeholderText="MM-DD-YYYY"
                  className="form-control"
                  minDate={
                    formData.start_date_of_jury_selection
                      ? new Date(formData.start_date_of_jury_selection)
                      : new Date()
                  }
                />
              </div>
            </div>
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>
                  Status <span className="text-danger">*</span>
                </label>

                <CustomSelect
                  name="case_status"
                  value={formData.case_status}
                  onChange={handleChange}
                  placeholder="Select Status"
                  options={[
                    { value: "waiting", label: "Waiting" },
                    { value: "active", label: "Active" },
                    { value: "inactive", label: "Inactive" },
                    { value: "archived", label: "Archived" },
                  ]}
                />
              </div>
            </div>
            {/* Description */}
            <div className="col-12">
              <div className="datafrm">
                <label>Case Description</label>
                <textarea
                  name="case_desc"
                  value={formData.case_desc}
                  onChange={handleChange}
                  placeholder="Enter detailed case description"
                ></textarea>
              </div>
            </div>

            {/* Key Phases */}
            {/* <div className="col-lg-6 col-sm-6"> */}
            <div className="col-12">
              <div className="datafrm">
                <label>Key Phrases for Ideal Juror</label>
                <input
                  type="text"
                  name="key_phases_for_ideal_juror"
                  value={formData.key_phases_for_ideal_juror}
                  onChange={handleChange}
                  placeholder="Phrases 1, Phrases 2"
                />
              </div>
            </div>

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

                <select
                  name="status"
                  value={formData.status}
                  onChange={handleChange}
                  className="form-control"
                >
                  <option value="">Select status</option>
                  <option value="waiting">Waiting</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                  <option value="archived">Archived</option>
                </select>
              </div>
            </div> */}

            {uploadFiles.length > 0 && (
              <div className="uploaded-documents-section">
                <h4 className="uploaded-title">
                  Uploaded Documents ({uploadFiles.length})
                </h4>
                <p className="uploaded-subtitle">
                  Documents attached to this case
                </p>

                <div className="uploaded-list">
                  {uploadFiles.map((file, idx) => (
                    <div className="uploaded-file-pill" key={idx}>
                      <div className="pill-icon">
                        <span>📄</span>
                      </div>

                      <div className="pill-content">
                        <div className="pill-name">{file.name}</div>
                        <div className="pill-meta">
                          {file.typeLabel || "Document"} •{" "}
                          {file.sizeLabel || "1.2 MB"}
                        </div>
                      </div>

                      <button
                        type="button"
                        className="pill-remove"
                        onClick={() => onRemoveFile(idx)}
                      >
                        ×
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Submit */}
            <div className="col-12">
              <div className="datafrmbtn">
                <input
                  type="submit"
                  value={loading ? "Creating case..." : "Create Case"}
                  disabled={loading}
                />
              </div>
            </div>
          </div>
        </form>
      </div>
      <UploadModal
        isOpen={isUploadModalOpen}
        onClose={() => setIsUploadModalOpen(false)}
        onFileSelect={handleModalFileSelect}
        onUpload={handleModalUpload}
      />
    </Layout>
  );
}
