import React, { useEffect, useState } from "react";
import Layout from "../../Layout";
import { getAllJurorsToCaseView, getCaseById } from "@/services/caseService";
import { useParams } from "next/navigation";
import { ClipLoader } from "react-spinners";
import { toast } from "react-toastify";
import Link from "next/link";
import { useProfile } from "@/context/ProfileContext";
import { assetPath } from "@/utils/assetPath";
import { formatDate } from "@/utils/dateFormat";
import { getAllJurorsToCase } from "@/services/caseService";
import { getDocumentsCase } from "@/services/caseService";
import EditJurorModal from "@/components/admin/case-management/edit-juror/EditJurorModal";

const Item = ({ label, value }) => (
  <div className="col-md-4 col-6 mb-3">
    <div className="viewitem">
      <strong>{label}</strong>
      <div>{value || "-"}</div>
    </div>
  </div>
);

export default function ViewCase() {
  const { profile } = useProfile();

  const isAnalyst = profile?.role_details?.[0]?.name?.includes("Analyst");
  const { id } = useParams();

  const [caseData, setCaseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [jurors, setJurors] = useState([]);
  const [jurorsLoading, setJurorsLoading] = useState(false);
  const [documents, setDocuments] = useState([]);
  const [documentsLoading, setDocumentsLoading] = useState(false);
  const [selectedJurorId, setSelectedJurorId] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);

  useEffect(() => {
    if (id) {
      fetchJurors();
      fetchDocuments();
    }
  }, [id]);

  const fetchJurors = async () => {
    try {
      setJurorsLoading(true);

      const res = await getAllJurorsToCaseView(id);

      setJurors(res?.data?.results || []);
    } catch (error) {
      console.error("Error fetching jurors:", error);
    } finally {
      setJurorsLoading(false);
    }
  };

  const fetchDocuments = async () => {
    try {
      setDocumentsLoading(true);

      const res = await getDocumentsCase(id);

      setDocuments(res?.data?.documents || []);
    } catch (err) {
      console.error("Error fetching documents:", err);
    } finally {
      setDocumentsLoading(false);
    }
  };

  useEffect(() => {
    fetchCaseData();
  }, [id]);

  const fetchCaseData = async () => {
    try {
      setLoading(true);
      const res = await getCaseById(id);
      setCaseData(res.data);
    } catch (err) {
      console.error("Error fetching case:", err);
      toast.error("Failed to fetch case data");
    } finally {
      setLoading(false);
    }
  };

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

  //console.log(canEdit);

  function PersonList({ people, emptyText }) {
    if (!people?.length) return emptyText;

    return (
      <ul className="person-status-list">
        {people.map((p, idx) => (
          <li key={p.id ?? idx} className="d-flex align-items-center gap-2">
            <span
              className="status-dot"
              style={{
                backgroundColor:
                  p.status === "available" ? "#2ecc71" : "#e74c3c",
              }}
            ></span>
            {p.name}
          </li>
        ))}
      </ul>
    );
  }

  if (loading) {
    return (
      <Layout title="Loading...">
        <div
          className="d-flex justify-content-center align-items-center"
          style={{ minHeight: "300px" }}
        >
          <ClipLoader size={30} color="#0C3155" />
        </div>
      </Layout>
    );
  }

  return (
    <Layout title="View Case">
      <div className="pagerlink">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>
            <Link href="/case-list">All Cases</Link>
          </li>
          <li>View Case</li>
        </ul>
      </div>

      <div className="d-flex justify-content-between align-items-center flex-wrap mb-4 border-bottom pb-3">
        <div>
          <div className="d-flex align-items-center gap-2 flex-wrap">
            <h2 className="mb-0">{caseData?.name || "-"}</h2>

            <span
              className={`badge ${
                caseData?.case_status === "waiting"
                  ? "bg-warning text-dark"
                  : caseData?.case_status === "active"
                    ? "bg-primary"
                    : caseData?.case_status === "archived" ||
                        caseData?.case_status === "inactive"
                      ? "bg-secondary"
                      : "bg-success"
              }`}
            >
              {caseData?.case_status
                ?.replace(/_/g, " ")
                .replace(/\b\w/g, (c) => c.toUpperCase())}
            </span>

            <span
              className={`badge ${
                caseData?.priority === "high"
                  ? "bg-danger"
                  : caseData?.priority === "medium"
                    ? "bg-warning text-dark"
                    : "bg-info text-dark"
              }`}
            >
              {caseData?.priority
                ? caseData.priority.charAt(0).toUpperCase() +
                  caseData.priority.slice(1)
                : "-"}
            </span>
          </div>

          <p className="text-muted mb-0 mt-1">
            <strong>Case ID:</strong> {caseData?.case_id || "-"}
          </p>
        </div>
      </div>

      <div className="dshboardwhtepnel my-3">
        <div className="casestablelist">
          <div className="d-flex justify-content-between align-items-center mb-2">
            <h5>List of Jurors ({jurors.length})</h5>
            {canEdit && (
              <Link
                className="heading-btn"
                href={`/case-list/edit-case/${caseData?.id}`}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                >
                  <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
                  <path
                    fillRule="evenodd"
                    d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5z"
                  />
                </svg>

                <span>Edit Case</span>
              </Link>
            )}
          </div>

          {jurorsLoading ? (
            <div className="text-center py-3">
              <ClipLoader size={24} color="#0C3155" />
            </div>
          ) : (
            <div className="table-responsive">
              <table>
                <thead>
                  <tr>
                    <th>Juror #</th>
                    <th>Juror Name</th>
                    <th>Analyst</th>
                    <th>Status</th>
                  </tr>
                </thead>

                <tbody>
                  {jurors.length > 0 ? (
                    jurors.map((juror) => (
                      <tr key={juror.id}>
                        <td
                          style={{ cursor: "pointer", color: "#007bff" }}
                          onClick={() => {
                            setSelectedJurorId(juror.juror_id);
                            setShowEditModal(true);
                          }}
                        >
                          {juror.juror_number}
                        </td>

                        <td>
                          {[
                            juror.first_name,
                            juror.middle_name,
                            juror.last_name,
                          ]
                            .filter(Boolean)
                            .join(" ")}
                        </td>

                        <td>{juror.analyst_name || "N/A"}</td>

                        <td>
                          {juror.status
                            ?.replace(/_/g, " ")
                            ?.replace(/\b\w/g, (c) => c.toUpperCase())}
                        </td>
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td colSpan="4" className="text-center">
                        No jurors assigned to this case.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      <div className="dshboardwhtepnel">
        <div className="viewlist">
          <div className="d-flex justify-content-between align-items-center mb-2">
            <h5>Court and Case Information </h5>

            {/* {canEdit && ( */}
            {/* {canEdit && (
              <Link
                className="heading-btn"
                href={`/case-list/edit-case/${caseData?.id}`}
              >
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  fill="currentColor"
                  viewBox="0 0 16 16"
                >
                  <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z" />
                  <path
                    fillRule="evenodd"
                    d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5z"
                  />
                </svg>

                <span>Edit Case</span>
              </Link>
            )} */}
            {/* )} */}
          </div>

          <div className="row gx-2">
            {/* <Item label="Case ID" value={caseData?.case_id} />
            <Item label="Case Name" value={caseData?.name} /> */}
            <Item label="Case Type" value={caseData?.case_type} />
            {/* <Item label="Case Status" value={caseData?.case_status} />
            <Item label="Priority" value={caseData?.priority} /> */}
            {/* <div className="col-lg-4 col-md-6 mb-3">
              <div className="viewitem">
                <span>Case Status</span>

                <h6>
                  <span
                    className={
                      caseData?.case_status === "waiting"
                        ? "pndngmsg"
                        : caseData?.case_status === "active"
                          ? "prgresmsg"
                          : caseData?.case_status === "archived"
                            ? "archvedmsg"
                            : caseData?.case_status === "inactive"
                              ? "archvedmsg"
                              : "cmpltemsg"
                    }
                  >
                    {caseData?.case_status
                      ?.replace(/_/g, " ")
                      .replace(/\b\w/g, (char) => char.toUpperCase())}
                  </span>
                </h6>
              </div>
            </div> */}

            {/* <div className="col-lg-4 col-md-6 mb-3">
              <div className="viewitem">
                <span>Priority</span>

                <h6>
                  <span
                    className={
                      caseData?.priority === "high"
                        ? "redmesg"
                        : caseData?.priority === "medium"
                          ? "mdiamesg"
                          : "outlnemsg"
                    }
                  >
                    {caseData?.priority
                      ? caseData.priority.charAt(0).toUpperCase() +
                        caseData.priority.slice(1)
                      : "-"}
                  </span>
                </h6>
              </div>
            </div> */}
            <Item
              label="Jury Selection Date"
              value={
                caseData?.start_date_of_jury_selection
                  ? formatDate(caseData?.start_date_of_jury_selection)
                  : "-"
              }
            />
            <Item
              label="Deadline"
              value={caseData?.deadline ? formatDate(caseData.deadline) : "-"}
            />

            <div className="col-12 mb-3">
              <div className="viewitem">
                <strong>Court Name and Location</strong>
                <div>
                  {`${caseData?.court_name} (${caseData?.court_type}): ` +
                    `${caseData?.city} (${caseData?.county}), ${caseData?.state_short_name}` ||
                    "-"}
                </div>
              </div>
            </div>
            {/* <Item
              label="Court Name and Location"
              value={
                `${caseData?.court_name} (${caseData?.court_type}): ` +
                `${caseData?.city} (${caseData?.county}), ${caseData?.state_short_name}`
              }
            /> */}
            <Item label="Jurisdiction" value={caseData?.jurisdiction} />
            <Item label="Judge Name" value={caseData?.judge_name} />
          </div>
          <h5>Juror Requirements</h5>

          <div className="row gx-2">
            <Item
              label="Ideal Juror Keywords"
              value={caseData?.key_phases_for_ideal_juror}
            />

            <Item
              label="Warning Sign Keywords"
              value={caseData?.key_phases_for_warn_sign}
            />
          </div>
        </div>

        {/* <div className="viewlist"> */}
        {/* <h5>Court Information</h5> */}

        {/* <div className="row gx-2"> */}
        {/* <Item label="Court System" value={caseData?.court_system} /> */}
        {/* <Item label="City" value={caseData?.city} />
            <Item label="County" value={caseData?.county} />
            <Item
              label="State"
              value={`${caseData?.state_name} (${caseData?.state_short_name})`}
            /> */}

        {/* <Item label="Jurisdiction" value={caseData?.jurisdiction} />
             <Item label="Court Type" value={caseData?.court_type} />
            <Item label="Judge Name" value={caseData?.judge_name} /> */}
        {/* </div> */}
        {/* </div> */}

        {/* <div className="viewlist">
          <h5>Assignment Information</h5>

          <div className="row gx-2">
            <Item
              label="Lead Attorney"
              value={caseData?.lead_attorney}
            />

            <Item
              label="Lead Analyst"
              value={caseData?.lead_consultant}
            />

            <Item
              label="Lead Attorney ID"
              value={caseData?.lead_attorney_id}
            />

            <Item
              label="Lead Analyst ID"
              value={caseData?.lead_consultant_id}
            />
          </div>
        </div> */}

        <div className="viewlist">
          <h5>Case Description</h5>

          <div className="row">
            <div className="col-12">
              <div className="viewitem">
                <span>Description</span>
                <h6>{caseData?.case_desc || "-"}</h6>
              </div>
            </div>
          </div>
        </div>

        {/* <div className="viewlist">
          <h5>Juror Requirements</h5>

          <div className="row gx-2">
            <Item
              label="Ideal Juror Keywords"
              value={caseData?.key_phases_for_ideal_juror}
            />

            <Item
              label="Warning Sign Keywords"
              value={caseData?.key_phases_for_warn_sign}
            />
          </div>
        </div> */}

        {/* <div className="viewlist">
          <h5>Assigned Members</h5>

          <div className="row">
            <div className="col-12">
              <div className="viewitem">
                <span>Member IDs</span>
                <h6>
                  {caseData?.members?.length
                    ? caseData.members.join(", ")
                    : "-"}
                </h6>
              </div>
            </div>
          </div>
        </div>

        <div className="viewlist">
          <h5>System Information</h5>

          <div className="row gx-2">
            <Item label="Created At" value={caseData?.created_at} />
            <Item label="Updated At" value={caseData?.updated_at} />
          </div>
        </div> */}
      </div>

      <div className="dshboardwhtepnel mt-3">
        <div className="viewlist">
          <h5>Documents ({documents.length})</h5>

          {documentsLoading ? (
            <div className="text-center py-3">
              <ClipLoader size={24} color="#0C3155" />
            </div>
          ) : documents.length > 0 ? (
            <div className="uploaded-list">
              {documents.map((doc, index) => (
                <div
                  key={doc.document_id || index}
                  className="uploaded-file-pill"
                >
                  <a
                    href={doc.file_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="uploaded-link"
                  >
                    <div className="pill-icon">📄</div>

                    <div className="pill-content">
                      <div className="pill-name">
                        {doc.file_name || `Document ${index + 1}`}
                      </div>

                      <div className="pill-meta">Click to view document</div>
                    </div>
                  </a>
                </div>
              ))}
            </div>
          ) : (
            <p>No documents uploaded.</p>
          )}
        </div>
      </div>

      {canEdit && (
        <div className="dshboardwhtepnel mt-3">
          <div className="viewlist">
            <div className="d-flex gap-3 mb-3">
              <h5 className="mb-0">Team Assignment</h5>
              <div className="d-flex align-items-center align-self-center gap-2 gap-md-3">
                <div className="statusbx">
                  <span
                    className="status-dot"
                    style={{ background: "#2ecc71" }}
                  ></span>
                  <span>Available</span>
                </div>
                <div className="statusbx">
                  <span
                    className="status-dot"
                    style={{ background: "#e74c3c" }}
                  ></span>
                  <span>Busy</span>
                </div>
              </div>
            </div>

            <div className="row gx-2 gx-md-4">
              <Item label="Lead Attorney" value={caseData?.lead_attorney} />
              <Item label="Lead Analyst" value={caseData?.lead_consultant} />
            </div>

            {/* <div className="row gx-2 gx-md-4">
            <Item
              label="Analysts"
              value={
                caseData?.analysts?.length > 0
                  ? caseData.analysts.map((p) => p.name).join(", ")
                  : "No analysts assigned"
              }
            />

            <Item
              label="Attorneys"
              value={
                caseData?.attorneys?.length > 0
                  ? caseData.attorneys.map((p) => p.name).join(", ")
                  : "No attorneys assigned"
              }
            />

            <Item
              label="Paralegals"
              value={
                caseData?.paralegals?.length > 0
                  ? caseData.paralegals.map((p) => p.name).join(", ")
                  : "No paralegals assigned"
              }
            />
          </div> */}

            <div className="row gx-2 gx-md-4">
              <Item
                label="Analysts"
                value={
                  <PersonList
                    people={caseData?.analysts}
                    emptyText="No analysts assigned"
                  />
                }
              />

              <Item
                label="Attorneys"
                value={
                  <PersonList
                    people={caseData?.attorneys}
                    emptyText="No attorneys assigned"
                  />
                }
              />

              <Item
                label="Paralegals"
                value={
                  <PersonList
                    people={caseData?.paralegals}
                    emptyText="No paralegals assigned"
                  />
                }
              />
            </div>
          </div>
        </div>
      )}

      <EditJurorModal
        caseId={id}
        jurorId={selectedJurorId}
        open={showEditModal}
        onClose={() => setShowEditModal(false)}
        onUpdated={fetchJurors}
      />
    </Layout>
  );
}
