import React, { useEffect, useState } from "react";
import Layout from "../../Layout";
import ViewCaseInfo from "../../components/admin/case-management/tabs/ViewCaseInfo";
import AddJurors from "../../components/admin/case-management/tabs/AddJurors";
import ManageJurors from "../../components/admin/case-management/tabs/ManageJurors";
import Documents from "../../components/admin/case-management/tabs/Documents";
import { getCaseById, editCaseById } from "@/services/caseService";
import { useParams, useSearchParams } from "next/navigation";
import useNavigate from "@/hooks/useNavigate";
import { ClipLoader } from "react-spinners";
import { toast } from "react-toastify";
import AddJurorsUpdated from "@/components/admin/case-management/tabs/AddJurorsUpdated";
import { data } from "jquery";
import AssigningAnalystAttorney from "@/components/admin/case-management/tabs/AssigningAnalystAttorney";
import Link from "next/link";
import { useProfile } from "@/context/ProfileContext";
import { formatDate } from "@/utils/dateFormat";
import AssignJurorByAnalyst from "@/components/admin/case-management/tabs/AssignJurorByAnalyst";

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

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

  const { id } = useParams();
  const [activeTab, setActiveTab] = useState("Case Details");
  const [caseData, setCaseData] = useState(null);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const searchParams = useSearchParams();
  const page = searchParams.get("page") || 1;

  const canViewTabs =
    !isAnalyst || Number(caseData?.lead_consultant_id) === Number(profile?.id);
  useEffect(() => {
    fetchCaseData();
  }, [id]);

  const canViewLeadTabs =
    Number(caseData?.lead_consultant_id) === Number(profile?.id);

  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 handleUpdate = async (changedFields) => {
    if (!changedFields || Object.keys(changedFields).length === 0) {
      toast.info("No changes to update");
      return;
    }

    try {
      // Convert Date objects to ISO strings
      const payload = { ...changedFields };
      if (payload.start_date_of_jury_selection)
        payload.start_date_of_jury_selection =
          payload.start_date_of_jury_selection.toISOString().split("T")[0];
      if (payload.deadline)
        payload.deadline = payload.deadline.toISOString().split("T")[0];

      await editCaseById(id, payload);
      toast.success("Case updated successfully!");
      fetchCaseData(); // refresh case data
    } 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");
      }
    }
  };

  const renderTabContent = () => {
    switch (activeTab) {
      case "Case Details":
        return <ViewCaseInfo data={caseData} onUpdate={handleUpdate} />;
      case "Manage Team":
        return <AssigningAnalystAttorney data={caseData} />;
      // case "Add Juror/s":
      //   return canViewTabs ? <AddJurorsUpdated data={caseData} /> : null;
      case "Manage Juror":
        return <ManageJurors data={caseData} />;
      case "Researching Jurors":
        return <AssignJurorByAnalyst data={caseData} />;

      case "Case Documents":
        return canViewTabs ? <Documents data={caseData} /> : null;
      default:
        return <ViewCaseInfo data={caseData} onUpdate={handleUpdate} />;
    }
  };

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

  return (
    <Layout title="All Cases">
      <div className="pagerlink">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>
            {/* <Link href="/case-list">All Cases</Link> */}
            <Link href={`/case-list?page=${page}`}>All Cases</Link>
          </li>
          <li>{activeTab}</li>
        </ul>
      </div>

      <div className="topheading">
        <h2>{caseData?.name}</h2>
        <p>Case ID: {caseData?.case_id}</p>
      </div>

      <div className="cuntingdshbrd mb-3">
        <div className="row">
          <div className="col-3">
            <div className="cuntingnmber cuntingnmberinner">
              <span>Priority</span>
              <h5>{caseData?.priority ?? "-"}</h5>
            </div>
          </div>

          <div className="col-3">
            <div className="cuntingnmber cuntingnmberinner">
              <span>Deadline</span>
              <h5>{formatDate(caseData?.deadline ?? "-")}</h5>
            </div>
          </div>

          <div className="col-3">
            <div className="cuntingnmber cuntingnmberinner">
              <span>Lead Analyst</span>
              <h5 className="text-truncate">
                {caseData?.lead_consultant ?? "-"}
              </h5>
            </div>
          </div>

          <div className="col-3">
            <div className="cuntingnmber cuntingnmberinner">
              <span>Documents</span>
              <h5>{caseData?.document_count ?? "0"} Files</h5>
            </div>
          </div>

          <div className="col-3">
            <div className="cuntingnmber cuntingnmberinner">
              <span>Assigned Jurors</span>
              {/* <h5>{caseData?.members.length ?? 0}</h5> */}
              <h5>{caseData?.juror_count ?? "-"}</h5>
            </div>
          </div>
        </div>
      </div>

      <div className="dshboardwhtepnel mt-3">
        <div
          className={`tab-header-box ${
            canViewTabs ? "" : "justify-content-center"
          }`}
        >
          {[
            "Case Details",
            "Manage Team",
            // ...(canViewTabs ? ["Add Juror/s"] : []),
            "Manage Juror",
            ...(canViewLeadTabs ? ["Researching Jurors"] : []),
            ...(canViewTabs ? ["Case Documents"] : []),
          ].map((tab) => (
            <button
              key={tab}
              className={`tab-btn ${activeTab === tab ? "active" : ""}`}
              onClick={() => setActiveTab(tab)}
            >
              {tab}
            </button>
          ))}
        </div>

        <div className="tab-container">{renderTabContent()}</div>
      </div>
    </Layout>
  );
}
