"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/app/shadcn_components/ui/tabs";
import { Card, CardContent } from "@/app/shadcn_components/ui/card";
import {
  BarChart2,
  Table2,
  FolderOpen,
  Wrench,
  AlertTriangle,
} from "lucide-react";
import DrillDownTable from "./DrillDownTable";
import PropertyTable from "./PropertyTable";
import DocumentTable from "./DocumentTable";
import MeasuresTable from "./MeasuresTable";
import type { HubspotDeal } from "./types";
import PropertyDrawer from "./PropertyDrawer";
import PropertyDetailDrawer from "./PropertyDetailDrawer";
import AnalyticsView from "./AnalyticsView";
import type {
  LiveTrackerProps,
  TableModal,
  ClassifiedDeal,
  DocumentDrawerState,
  DocStatusMap,
  RemovalStatusByDeal,
} from "./types";

export default function LiveTracker({
  projects,
  totalDeals,
  majorConditionDeals,
  docStatusMap,
  userCapability,
  approvalsByDeal,
  removalStatusByDeal,
  portfolioId,
  userRole,
  userEmail,
}: LiveTrackerProps) {
  // ── Tab state ────────────────────────────────────────────────────────
  const [activeTab, setActiveTab] = useState<
    "analytics" | "properties" | "documents" | "measures"
  >("analytics");

  // ── Project selector (shared across both tabs) ───────────────────────
  const projectCodes = projects.map((p) => p.projectCode);
  const [currentProjectCode, setCurrentProjectCode] = useState(projectCodes[0]);
  const currentProject = projects.find(
    (p) => p.projectCode === currentProjectCode,
  );

  // ── Pending removal count for current project ────────────────────────
  const pendingRemovalCount = (currentProject?.allDeals ?? []).filter((d) => {
    const state = d.dealId ? removalStatusByDeal[d.dealId] : undefined;
    return state === "pending_removal" || state === "pending_re_addition";
  }).length;

  // ── Drill-down table modal (used by AnalyticsView) ───────────────────
  const [openTable, setOpenTable] = useState<TableModal | null>(null);

  // ── Document drawer (used by PropertyTable) ──────────────────────────
  const [drawerState, setDrawerState] = useState<DocumentDrawerState>({
    open: false,
    dealId: null,
    uprn: null,
    landlordPropertyId: null,
    dealname: null,
  });

  // ── Property detail drawer ───────────────────────────────────────────
  const [detailDeal, setDetailDeal] = useState<ClassifiedDeal | null>(null);

  const handleOpenTable = (
    stage: string,
    filteredDeals: ClassifiedDeal[],
    columns?: (keyof ClassifiedDeal)[],
    columnLabels?: Partial<Record<keyof ClassifiedDeal, string>>,
    breakdown?: Record<string, ClassifiedDeal[]>,
  ) => {
    setOpenTable({
      stage,
      data: filteredDeals,
      columns: (columns || [
        "dealname",
        "landlordPropertyId",
      ]) as (keyof ClassifiedDeal)[],
      columnLabels: (columnLabels || {
        dealname: "Address Ref.",
        landlordPropertyId: "Property Ref.",
      }) as Partial<Record<keyof ClassifiedDeal, string>>,
      breakdown,
    });
  };

  const handleOpenDrawer = (
    dealId: string,
    uprn: string | null,
    landlordPropertyId: string | null,
    dealname: string | null,
  ) => {
    setDrawerState({ open: true, dealId, uprn, landlordPropertyId, dealname });
  };

  if (!totalDeals) {
    return (
      <Card className="p-8 text-center bg-gradient-to-br from-brandlightblue/30 to-white border border-brandblue/10 shadow-sm">
        <CardContent>
          <p className="text-gray-600 text-sm">No deal data available.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-4 w-full">
      <Tabs
        value={activeTab}
        onValueChange={(v) =>
          setActiveTab(
            v as "analytics" | "properties" | "documents" | "measures",
          )
        }
      >
        {/* Tab bar */}
        <TabsList className="h-10 p-1 bg-brandlightblue/10 border border-brandblue/10 rounded-xl mb-6">
          <TabsTrigger
            value="analytics"
            className="flex items-center gap-2 rounded-lg text-sm font-medium px-4 data-[state=active]:bg-white data-[state=active]:text-brandblue data-[state=active]:shadow-sm transition-all"
          >
            <BarChart2 className="h-3.5 w-3.5" />
            Analytics
          </TabsTrigger>
          <TabsTrigger
            value="properties"
            className="flex items-center gap-2 rounded-lg text-sm font-medium px-4 data-[state=active]:bg-white data-[state=active]:text-brandblue data-[state=active]:shadow-sm transition-all"
          >
            <Table2 className="h-3.5 w-3.5" />
            Properties
            <span
              className={`ml-1 min-w-[18px] h-[18px] px-1 rounded-full bg-amber-500 text-white text-[10px] font-bold flex items-center justify-center leading-none transition-opacity ${
                pendingRemovalCount > 0
                  ? "opacity-100"
                  : "opacity-0 pointer-events-none"
              }`}
              aria-hidden={pendingRemovalCount === 0}
            >
              {pendingRemovalCount || ""}
            </span>
          </TabsTrigger>
          <TabsTrigger
            value="documents"
            className="flex items-center gap-2 rounded-lg text-sm font-medium px-4 data-[state=active]:bg-white data-[state=active]:text-brandblue data-[state=active]:shadow-sm transition-all"
          >
            <FolderOpen className="h-3.5 w-3.5" />
            Documents
          </TabsTrigger>
          <TabsTrigger
            value="measures"
            className="flex items-center gap-2 rounded-lg text-sm font-medium px-4 data-[state=active]:bg-white data-[state=active]:text-brandblue data-[state=active]:shadow-sm transition-all"
          >
            <Wrench className="h-3.5 w-3.5" />
            Measures
          </TabsTrigger>
        </TabsList>

        {/* Analytics tab */}
        <TabsContent value="analytics" className="mt-0">
          {currentProject && (
            <AnalyticsView
              projects={projects}
              currentProject={currentProject}
              currentProjectCode={currentProjectCode}
              onProjectChange={setCurrentProjectCode}
              onOpenTable={handleOpenTable}
              majorConditionDeals={majorConditionDeals}
              totalDeals={totalDeals}
            />
          )}
        </TabsContent>

        {/* Properties tab */}
        <TabsContent value="properties" className="mt-0">
          <div className="space-y-4">
            {/* Project selector — mirrors analytics tab */}
            {projects.length > 1 && (
              <div className="flex items-center gap-3">
                <span className="text-sm text-gray-500 shrink-0">Project:</span>
                <select
                  value={currentProjectCode}
                  onChange={(e) => setCurrentProjectCode(e.target.value)}
                  className="px-3 py-1.5 border border-brandblue/20 rounded-lg bg-white text-sm text-gray-800 font-medium focus:ring-2 focus:ring-brandblue focus:border-brandblue focus:outline-none transition-all appearance-none pr-8"
                >
                  {projectCodes.map((code) =>
                    code === "__ALL__" ? (
                      <option
                        key="__ALL__"
                        value="__ALL__"
                        style={{ fontWeight: 700 }}
                      >
                        ★ All Projects
                      </option>
                    ) : (
                      <option key={code} value={code}>
                        {code}
                      </option>
                    ),
                  )}
                </select>
              </div>
            )}

            <div
              className={`flex items-center gap-2.5 px-4 py-3 rounded-xl border border-amber-200 bg-amber-50 text-amber-800 text-sm ${pendingRemovalCount === 0 ? "hidden" : ""}`}
            >
              <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
              <span>
                <span className="font-semibold">{pendingRemovalCount}</span>{" "}
                {pendingRemovalCount === 1 ? "property has" : "properties have"}{" "}
                an outstanding removal request
              </span>
            </div>
            <PropertyTable
              data={currentProject?.allDeals ?? []}
              onOpenDrawer={handleOpenDrawer}
              onOpenDetail={setDetailDeal}
              docStatusMap={docStatusMap}
              removalStatusByDeal={removalStatusByDeal}
            />
          </div>
        </TabsContent>
        {/* Document Management tab */}
        <TabsContent value="documents" className="mt-0">
          <div className="space-y-4">
            {projects.length > 1 && (
              <div className="flex items-center gap-3">
                <span className="text-sm text-gray-500 shrink-0">Project:</span>
                <select
                  value={currentProjectCode}
                  onChange={(e) => setCurrentProjectCode(e.target.value)}
                  className="px-3 py-1.5 border border-brandblue/20 rounded-lg bg-white text-sm text-gray-800 font-medium focus:ring-2 focus:ring-brandblue focus:border-brandblue focus:outline-none transition-all appearance-none pr-8"
                >
                  {projectCodes.map((code) =>
                    code === "__ALL__" ? (
                      <option
                        key="__ALL__"
                        value="__ALL__"
                        style={{ fontWeight: 700 }}
                      >
                        ★ All Projects
                      </option>
                    ) : (
                      <option key={code} value={code}>
                        {code}
                      </option>
                    ),
                  )}
                </select>
              </div>
            )}
            <DocumentTable
              data={currentProject?.allDeals ?? []}
              onOpenDrawer={handleOpenDrawer}
              docStatusMap={docStatusMap}
              portfolioId={portfolioId}
              userCapability={userCapability}
              approvalsByDeal={approvalsByDeal}
            />
          </div>
        </TabsContent>

        {/* Measures tab */}
        <TabsContent value="measures" className="mt-0">
          <div className="space-y-4">
            {projects.length > 1 && (
              <div className="flex items-center gap-3">
                <span className="text-sm text-gray-500 shrink-0">Project:</span>
                <select
                  value={currentProjectCode}
                  onChange={(e) => setCurrentProjectCode(e.target.value)}
                  className="px-3 py-1.5 border border-brandblue/20 rounded-lg bg-white text-sm text-gray-800 font-medium focus:ring-2 focus:ring-brandblue focus:border-brandblue focus:outline-none transition-all appearance-none pr-8"
                >
                  {projectCodes.map((code) =>
                    code === "__ALL__" ? (
                      <option
                        key="__ALL__"
                        value="__ALL__"
                        style={{ fontWeight: 700 }}
                      >
                        ★ All Projects
                      </option>
                    ) : (
                      <option key={code} value={code}>
                        {code}
                      </option>
                    ),
                  )}
                </select>
              </div>
            )}
            <MeasuresTable
              data={currentProject?.allDeals ?? []}
              userCapability={userCapability}
              approvalsByDeal={approvalsByDeal}
              portfolioId={portfolioId}
            />
          </div>
        </TabsContent>
      </Tabs>

      {/* ── Drill-down table modal ─────────────────────────────────────── */}
      {openTable && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-md transition-opacity"
          onClick={() => setOpenTable(null)}
        >
          <motion.div
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.2 }}
            className="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-6xl h-[90vh] flex flex-col border border-brandblue/10"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="mb-6 border-b border-brandblue/10 pb-6">
              <h2 className="text-2xl font-bold text-brandblue mb-3">
                {openTable.stage}
              </h2>
              <p className="text-sm text-gray-600 mb-4">
                Showing{" "}
                <span className="font-semibold text-brandblue">
                  {openTable.data.length}
                </span>{" "}
                properties
              </p>

              {openTable.breakdown && (
                <div className="grid grid-cols-2 gap-3">
                  {Object.entries(openTable.breakdown).map(
                    ([category, items]) => {
                      const isCompleted = category.includes("Complete");
                      const bgColor = isCompleted
                        ? "bg-gradient-to-br from-brandblue/25 to-brandblue/15"
                        : "bg-gradient-to-br from-amber-100/40 to-amber-50/30";
                      const borderColor = isCompleted
                        ? "border-brandblue/40"
                        : "border-amber-200/50";
                      const textColor = isCompleted
                        ? "text-brandblue"
                        : "text-amber-600";
                      const labelColor = isCompleted
                        ? "text-brandblue"
                        : "text-amber-600/70";

                      return (
                        <div
                          key={category}
                          className={`${bgColor} rounded-lg p-3 border ${borderColor}`}
                        >
                          <p
                            className={`text-xs uppercase tracking-wide font-semibold ${labelColor} mb-1`}
                          >
                            {category}
                          </p>
                          <p className={`text-2xl font-bold ${textColor}`}>
                            {items.length}
                          </p>
                          <p className="text-xs text-gray-500 mt-1">
                            {((items.length / openTable.data.length) * 100) | 0}
                            % of total
                          </p>
                        </div>
                      );
                    },
                  )}
                </div>
              )}
            </div>

            <div className="flex-1 overflow-auto rounded-lg border border-gray-100 bg-white p-4">
              <DrillDownTable
                data={openTable.data}
                columns={openTable.columns as (keyof HubspotDeal)[]}
                columnLabels={openTable.columnLabels}
              />
            </div>

            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => setOpenTable(null)}
                className="px-6 py-2.5 bg-slate-100 text-slate-600 font-medium rounded-lg border border-slate-200 hover:bg-slate-200 transition-all duration-200"
              >
                Close
              </button>
            </div>
          </motion.div>
        </div>
      )}

      {/* ── Document drawer ────────────────────────────────────────────── */}
      <PropertyDrawer
        open={drawerState.open}
        dealId={drawerState.dealId}
        uprn={drawerState.uprn}
        landlordPropertyId={drawerState.landlordPropertyId}
        dealname={drawerState.dealname}
        docStatus={
          drawerState.dealId ? docStatusMap[drawerState.dealId] : undefined
        }
        onClose={() =>
          setDrawerState({
            open: false,
            dealId: null,
            uprn: null,
            landlordPropertyId: null,
            dealname: null,
          })
        }
      />

      {/* ── Property detail drawer ─────────────────────────────────────── */}
      <PropertyDetailDrawer
        deal={detailDeal}
        onClose={() => setDetailDeal(null)}
        portfolioId={portfolioId}
        userRole={userRole}
        userCapability={userCapability}
        userEmail={userEmail}
      />
    </div>
  );
}
