"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useSearchParams, useRouter } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/app/shadcn_components/ui/dialog";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/app/shadcn_components/ui/tooltip";
import { AlertTriangle, ChevronRight, ChevronDown } from "lucide-react";
import { sapToEpc, getEpcAccentClasses, parsePreSap } from "@/app/utils";
import { parseMeasures } from "@/app/lib/parseMeasures";
import { outOfOrderInstructionWarning } from "@/app/lib/softWarnings";
import type { ClassifiedDeal, PortfolioCapabilityType, DocStatus, EffectiveRemovalState, PropertyDocument } from "../types";
import PropertyDocumentsContent from "../PropertyDocumentsContent";
import { StageBadge } from "../ui";
import {
  InfoRow,
  MilestoneTimeline,
  formatDate,
  SectionHeader,
  SECTION_TITLES,
  WRITE_ROLES,
} from "../deal-detail/primitives";
import { MeasureApprovalEditor } from "../deal-detail/MeasureApprovalEditor";
import { InstructMeasureEditor } from "../deal-detail/pibi/InstructMeasureEditor";
import { PibiSurveysTabContent } from "../deal-detail/PibiSurveysTabContent";
import { ActivityLog } from "../ActivityLog";

type Tab = "works" | "pibi-surveys" | "documents";
const VALID_TABS: Tab[] = ["works", "pibi-surveys", "documents"];

const TAB_LABELS: Record<Tab, string> = {
  works: "Works",
  "pibi-surveys": "PIBIs & Surveys",
  documents: "Documents",
};

interface DealPageProps {
  deal: ClassifiedDeal;
  portfolioId: string;
  userRole: string;
  userCapability: PortfolioCapabilityType;
  approvedMeasures: string[];
  docStatus: DocStatus;
  removalState: EffectiveRemovalState;
  userEmail: string;
}

export default function DealPage({
  deal,
  portfolioId,
  userRole,
  userCapability,
  approvedMeasures,
  docStatus,
  removalState,
}: DealPageProps) {
  const searchParams = useSearchParams();
  const router = useRouter();
  const rawTab = searchParams.get("tab");
  const [activeTab, setActiveTab] = useState<Tab>(
    VALID_TABS.includes(rawTab as Tab) ? (rawTab as Tab) : "works",
  );
  const [instructModalOpen, setInstructModalOpen] = useState(false);
  const [isLogOpen, setIsLogOpen] = useState(false);

  const switchTab = (tab: Tab) => {
    setActiveTab(tab);
    router.replace(`?tab=${tab}`, { scroll: false });
  };

  const { data: documents = [], isFetching: docsFetching, isError: docsError } = useQuery({
    queryKey: ["property-documents", deal.dealId, deal.uprn, deal.landlordPropertyId],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (deal.dealId) params.set("dealId", deal.dealId);
      else if (deal.uprn) params.set("uprn", deal.uprn);
      else if (deal.landlordPropertyId) params.set("landlordPropertyId", deal.landlordPropertyId);
      const res = await fetch(`/api/live-tracking/property-documents?${params}`);
      if (!res.ok) throw new Error("Failed to load documents");
      return res.json() as Promise<PropertyDocument[]>;
    },
    staleTime: 30_000,
  });

  const parsedPreSap = parsePreSap(deal.preSapScore);
  const epcPotential = sapToEpc(deal.potentialPostSapScoreDropdown != null ? Number(deal.potentialPostSapScoreDropdown) : null);
  const technicalApprovedMeasures = parseMeasures(
    deal.technicalApprovedMeasuresForInstall ?? null,
  );
  const isApprover = userCapability.includes("approver");
  const canWrite = WRITE_ROLES.includes(userRole);

  return (
    <TooltipProvider>
      <div className="grid grid-cols-12 gap-6">

        {/* ── Left Sidebar: Property Info ─────────────────────────── */}
        <aside className="col-span-12 lg:col-span-3 space-y-5">
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 space-y-5">

            {/* Header info */}
            <div>
              <h2 className="text-base font-semibold text-gray-900 leading-snug mb-2">
                {deal.dealname ?? "Property"}
              </h2>
              <div className="flex flex-wrap items-center gap-1.5">
                <StageBadge stage={deal.displayStage} />
                {deal.landlordPropertyId && (
                  <span className="text-xs font-mono text-gray-400 bg-gray-50 px-2 py-0.5 rounded border border-gray-200">
                    {deal.landlordPropertyId}
                  </span>
                )}
              </div>
            </div>

            {/* Damp & mould flag */}
            {(deal.dampMouldFlag || deal.majorConditionIssuePhotosS3) && (
              <div className="flex items-start gap-2 p-3 rounded-lg bg-red-50 border border-red-200">
                <AlertTriangle className="h-3.5 w-3.5 text-red-500 mt-0.5 shrink-0" />
                <div>
                  <p className="text-xs font-semibold text-red-700">Damp & Mould Flag</p>
                  {deal.dampMouldFlag && (
                    <p className="text-xs text-red-600 mt-0.5">{deal.dampMouldFlag}</p>
                  )}
                  {deal.majorConditionIssueDescription && (
                    <p className="text-xs text-red-600 mt-0.5 italic">
                      {deal.majorConditionIssueDescription}
                    </p>
                  )}
                </div>
              </div>
            )}

            {/* EPC */}
            <div className="space-y-1.5">
              <p className="text-xs font-bold uppercase tracking-wider text-gray-400">
                Energy Performance
              </p>
              <div className="flex items-baseline gap-2">
                {parsedPreSap ? (
                  <span className={`text-2xl font-black ${getEpcAccentClasses(parsedPreSap.letter)}`}>
                    {parsedPreSap.display}
                  </span>
                ) : (
                  <span className="text-2xl font-black text-gray-400">—</span>
                )}
                {epcPotential !== "Unknown" && epcPotential !== (parsedPreSap?.letter ?? "Unknown") && (
                  <span className="text-sm text-gray-400">→ {epcPotential}</span>
                )}
              </div>
            </div>

            {/* Key details */}
            <div className="space-y-0.5 divide-y divide-gray-50">
              <InfoRow label="Project" value={deal.projectCode} />
              <InfoRow
                label="Group"
                value={
                  deal.batch
                    ? deal.batchDescription
                      ? `${deal.batch} — ${deal.batchDescription}`
                      : deal.batch
                    : null
                }
              />
              <InfoRow label="Coordinator" value={deal.coordinator} />
              <InfoRow label="Designer" value={deal.designer} />
              <InfoRow label="Installer" value={deal.installer} />
              <InfoRow label="Outcome" value={deal.outcome} />
              {deal.outcomeNotes && (
                <InfoRow label="Outcome Notes" value={deal.outcomeNotes} />
              )}
              <InfoRow label="Coordination" value={deal.coordinationStatus} />
              <InfoRow label="Design Status" value={deal.designStatus} />
              <InfoRow label="Design Type" value={deal.designType} />
              <InfoRow label="Lodgement Status" value={deal.lodgementStatus} />
              <InfoRow label="Measures Lodged" value={formatDate(deal.measuresLodgementDate)} />
              <InfoRow label="Full Lodgement" value={formatDate(deal.fullLodgementDate)} />
            </div>

            {/* Survey info */}
            <div className="space-y-0.5">
              <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-2">
                Survey
              </p>
              <div className="divide-y divide-gray-50">
                <InfoRow label="Survey Type" value={deal.surveyType} />
                <InfoRow
                  label="Surveyed"
                  value={formatDate(deal.surveyedDate)}
                />
                <InfoRow
                  label="Confirmed Date"
                  value={formatDate(deal.confirmedSurveyDate)}
                />
                <InfoRow
                  label="Confirmed Time"
                  value={deal.confirmedSurveyTime}
                />
              </div>
            </div>

          </div>
        </aside>

        {/* ── Center: Tabs ─────────────────────────────────────────── */}
        <section className="col-span-12 lg:col-span-6 space-y-4">
          {/* Tab bar */}
          <div className="flex gap-1 p-1 bg-brandlightblue/10 border border-brandblue/10 rounded-xl">
            {VALID_TABS.map((tab) => (
              <button
                key={tab}
                role="tab"
                data-testid={`deal-page-tab-${tab}`}
                aria-selected={activeTab === tab}
                onClick={() => switchTab(tab)}
                className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium transition-all ${
                  activeTab === tab
                    ? "bg-white text-brandblue shadow-sm"
                    : "text-gray-500 hover:text-gray-700"
                }`}
              >
                {TAB_LABELS[tab]}
              </button>
            ))}
          </div>

          <div className="bg-white rounded-xl border border-gray-200 shadow-sm">

            {/* ── Works ── */}
            <div
              className={`p-5 space-y-6 ${activeTab === "works" ? "block" : "hidden"}`}
            >
              {/* Measures */}
              <div>
                <SectionHeader id="measures" label={SECTION_TITLES.measures} />
                <div className="space-y-3">
                  <MeasureApprovalEditor
                    dealId={deal.dealId}
                    dealName={deal.dealname}
                    portfolioId={portfolioId}
                    proposedMeasures={parseMeasures(deal.proposedMeasures ?? null)}
                    isApprover={isApprover}
                  />
                </div>
                <div className="divide-y divide-gray-50 mt-3">
                  <InfoRow label="Installed" value={deal.actualMeasuresInstalled} />
                </div>
              </div>

              {/* Technical approved */}
              <div>
                <SectionHeader id="technical" label={SECTION_TITLES.technical} />
                <div className="divide-y divide-gray-50">
                  <InfoRow
                    label="Technical Approved Measures"
                    value={
                      technicalApprovedMeasures.length > 0 ? (
                        <span className="flex flex-wrap gap-1.5">
                          {technicalApprovedMeasures.map((m) => (
                            <span
                              key={m}
                              className="px-2 py-0.5 rounded-full text-[11px] bg-emerald-50 border border-emerald-200 text-emerald-700"
                            >
                              {m}
                            </span>
                          ))}
                        </span>
                      ) : null
                    }
                  />
                </div>
              </div>

              {/* Approval log */}
              <div className="border-t border-gray-100 pt-4">
                <button
                  onClick={() => setIsLogOpen((v) => !v)}
                  className="flex items-center gap-2 w-full text-left group"
                >
                  {isLogOpen ? (
                    <ChevronDown className="h-3.5 w-3.5 text-gray-400 group-hover:text-brandblue transition-colors shrink-0" />
                  ) : (
                    <ChevronRight className="h-3.5 w-3.5 text-gray-400 group-hover:text-brandblue transition-colors shrink-0" />
                  )}
                  <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 group-hover:text-brandblue transition-colors">
                    Approval Log
                  </h3>
                </button>
                {isLogOpen && (
                  <div className="mt-3">
                    <ActivityLog dealId={deal.dealId} portfolioId={portfolioId} />
                  </div>
                )}
              </div>
            </div>

            {/* ── PIBIs & Surveys ── */}
            <div
              className={`p-5 space-y-6 ${activeTab === "pibi-surveys" ? "block" : "hidden"}`}
            >
              <PibiSurveysTabContent
                deal={deal}
                portfolioId={portfolioId}
                userRole={userRole}
                userCapability={userCapability}
              />
            </div>

            {/* ── Documents ── */}
            <div
              className={`p-5 ${activeTab === "documents" ? "block" : "hidden"}`}
            >
              <PropertyDocumentsContent
                documents={documents}
                isFetching={docsFetching}
                isError={docsError}
                docStatus={docStatus}
                deal={deal}
                portfolioId={portfolioId}
                userCapability={userCapability}
                approvedMeasures={approvedMeasures}
              />
            </div>

          </div>
        </section>

        {/* ── Right Sidebar: Actions ───────────────────────────────── */}
        <aside className="col-span-12 lg:col-span-3 space-y-4">

          {/* Removal state badge */}
          {removalState !== "none" && (
            <div
              className={`flex items-center gap-2 px-3 py-2 rounded-lg border text-xs font-semibold ${
                removalState === "removed"
                  ? "bg-red-50 border-red-200 text-red-700"
                  : "bg-amber-50 border-amber-200 text-amber-700"
              }`}
            >
              <AlertTriangle className="h-3.5 w-3.5 shrink-0" />
              {removalState === "pending_removal"
                ? "Pending removal"
                : removalState === "pending_re_addition"
                  ? "Pending re-addition"
                  : "Removed from project"}
            </div>
          )}

          {/* Actions */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-4 space-y-2.5">
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">
              Actions
            </p>

            {/* Instruct Measure */}
            {isApprover ? (
              <button
                onClick={() => setInstructModalOpen(true)}
                className="w-full flex items-center justify-between px-4 py-3 rounded-lg bg-brandblue text-white text-sm font-semibold hover:bg-brandmidblue transition-colors"
              >
                <span>Instruct Measure</span>
                <span className="text-xs opacity-70">→</span>
              </button>
            ) : (
              <Tooltip>
                <TooltipTrigger asChild>
                  <button
                    disabled
                    className="w-full flex items-center justify-between px-4 py-3 rounded-lg bg-gray-100 text-gray-400 text-sm font-semibold cursor-not-allowed"
                  >
                    <span>Instruct Measure</span>
                    <span className="text-xs">→</span>
                  </button>
                </TooltipTrigger>
                <TooltipContent>Approver permission required</TooltipContent>
              </Tooltip>
            )}

            {/* Request Survey */}
            <button
              onClick={() => switchTab("pibi-surveys")}
              className="w-full flex items-center justify-between px-4 py-3 rounded-lg bg-gray-50 border border-gray-200 text-gray-700 text-sm font-semibold hover:border-brandblue/30 hover:text-brandblue transition-colors"
            >
              <span>Request Survey</span>
              <span className="text-xs opacity-50">→</span>
            </button>

            {/* Request Removal */}
            <button
              onClick={() => switchTab("pibi-surveys")}
              className="w-full flex items-center justify-between px-4 py-3 rounded-lg bg-gray-50 border border-gray-200 text-gray-700 text-sm font-semibold hover:border-brandblue/30 hover:text-brandblue transition-colors"
            >
              <span>Request Removal</span>
              <span className="text-xs opacity-50">→</span>
            </button>
          </div>

          {/* Timeline */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-4">
            <p className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">
              Project Timeline
            </p>
            <MilestoneTimeline deal={deal} />
          </div>
        </aside>

      </div>

      {/* ── Instruct Measure Modal ─────────────────────────────────── */}
      <Dialog open={instructModalOpen} onOpenChange={setInstructModalOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="text-base font-semibold text-brandblue">
              Instruct Measure
            </DialogTitle>
          </DialogHeader>
          <InstructMeasureEditor
            dealId={deal.dealId}
            portfolioId={portfolioId}
            proposedMeasures={parseMeasures(deal.proposedMeasures ?? null)}
            canEdit={isApprover}
            outOfOrderWarning={outOfOrderInstructionWarning(deal)}
            onSuccess={() => setInstructModalOpen(false)}
          />
        </DialogContent>
      </Dialog>

    </TooltipProvider>
  );
}
