"use client";

import { useEffect, useState } from "react";
import { X, ChevronRight, ChevronDown, AlertTriangle } from "lucide-react";
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/app/shadcn_components/ui/drawer";
import { parseMeasures } from "@/app/lib/parseMeasures";
import { outOfOrderInstructionWarning } from "@/app/lib/softWarnings";
import type { ClassifiedDeal, PortfolioCapabilityType } from "./types";
import { StageBadge } from "./ui";
import {
  type DrawerSection,
  SECTION_TITLES,
  InfoRow,
  SectionHeader,
  MilestoneTimeline,
  formatDate,
} 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 DrawerTab = "overview" | "works" | "pibi-surveys";

const SECTION_TO_TAB: Record<DrawerSection, DrawerTab> = {
  survey: "overview",
  measures: "works",
  technical: "works",
  pibi: "pibi-surveys",
  domna: "pibi-surveys",
};

const TAB_LABELS: Record<DrawerTab, string> = {
  overview: "Overview",
  works: "Works",
  "pibi-surveys": "PIBIs & Surveys",
};

interface PropertyDetailDrawerProps {
  deal: ClassifiedDeal | null;
  onClose: () => void;
  portfolioId: string;
  userRole: string;
  userCapability: PortfolioCapabilityType;
  userEmail: string;
  focusSection?: DrawerSection;
}

export default function PropertyDetailDrawer({
  deal,
  portfolioId,
  onClose,
  userRole,
  userCapability,
  focusSection,
}: PropertyDetailDrawerProps) {
  const open = !!deal;

  const [activeTab, setActiveTab] = useState<DrawerTab>(
    focusSection ? SECTION_TO_TAB[focusSection] : "overview",
  );
  const [isLogOpen, setIsLogOpen] = useState(false);

  useEffect(() => {
    setActiveTab(focusSection ? SECTION_TO_TAB[focusSection] : "overview");
  }, [focusSection, deal?.dealId]);

  const technicalApprovedMeasures = parseMeasures(
    deal?.technicalApprovedMeasuresForInstall ?? null,
  );

  const TABS: DrawerTab[] = ["overview", "works", "pibi-surveys"];

  return (
    <Drawer open={open} onOpenChange={(v) => !v && onClose()} direction="right">
      <DrawerContent
        data-testid="property-detail-drawer"
        className="fixed right-0 top-0 bottom-0 h-full w-[60vw] max-w-5xl rounded-l-2xl rounded-r-none mt-0 flex flex-col border-l border-t-0 border-b-0 border-r-0 border-brandblue/10 bg-white shadow-2xl overflow-hidden"
      >
        <div className="hidden" />

        {deal && (
          <>
            {/* ── Header ──────────────────────────────────────────────── */}
            <DrawerHeader className="shrink-0 px-6 pt-6 pb-0 border-b border-gray-100">
              <div className="flex items-start justify-between gap-3 pb-4">
                <div className="min-w-0 flex-1">
                  <DrawerTitle className="text-base font-semibold text-brandblue leading-snug line-clamp-2 mb-2">
                    {deal.dealname ?? "Property Details"}
                  </DrawerTitle>
                  <div className="flex flex-wrap items-center gap-2">
                    <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>
                    )}
                    {deal.projectCode && (
                      <span className="text-xs font-medium text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
                        {deal.projectCode}
                      </span>
                    )}
                  </div>
                </div>
                <DrawerClose asChild>
                  <button
                    onClick={onClose}
                    className="shrink-0 p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors"
                  >
                    <X className="h-4 w-4" />
                  </button>
                </DrawerClose>
              </div>

              <div className="flex gap-0 -mb-px">
                {TABS.map((tab) => (
                  <button
                    key={tab}
                    role="tab"
                    data-testid={`drawer-tab-${tab}`}
                    aria-selected={activeTab === tab}
                    onClick={() => setActiveTab(tab)}
                    className={`px-4 py-2.5 text-xs font-semibold border-b-2 transition-colors whitespace-nowrap ${
                      activeTab === tab
                        ? "border-brandblue text-brandblue"
                        : "border-transparent text-gray-400 hover:text-gray-600 hover:border-gray-200"
                    }`}
                  >
                    {TAB_LABELS[tab]}
                  </button>
                ))}
              </div>
            </DrawerHeader>

            {/* ── Tab panels ──────────────────────────────────────────── */}
            <div className="flex-1 overflow-y-auto">

              {/* ── Overview ── */}
              <div
                data-testid="drawer-tab-panel-overview"
                className={`px-6 py-5 space-y-6 ${activeTab === "overview" ? "block" : "hidden"}`}
              >
                {(deal.dampMouldFlag || deal.majorConditionIssuePhotosS3) && (
                  <div className="flex items-start gap-2.5 p-3.5 rounded-xl bg-red-50 border border-red-200">
                    <AlertTriangle className="h-4 w-4 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>
                )}

                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Property Details</h3>
                  <div className="divide-y divide-gray-50">
                    <InfoRow label="Coordinator" value={deal.coordinator} />
                    <InfoRow label="Designer" value={deal.designer} />
                    <InfoRow label="Installer" value={deal.installer} />
                    <InfoRow
                      label="Pre-SAP Score"
                      value={
                        deal.preSapScore
                          ? (() => {
                              const num = parseInt(deal.preSapScore.replace(/^[A-Za-z]+/, ""), 10);
                              return (
                                <span className={`font-semibold px-1.5 py-0.5 rounded text-xs ${
                                  num < 30
                                    ? "text-red-600 bg-red-50"
                                    : num < 50
                                      ? "text-amber-700 bg-amber-50"
                                      : "text-emerald-700 bg-emerald-50"
                                }`}>{deal.preSapScore}</span>
                              );
                            })()
                          : null
                      }
                    />
                    <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} />
                  </div>
                </div>

                <div>
                  <SectionHeader id="survey" label={SECTION_TITLES.survey} />
                  <div className="divide-y divide-gray-50">
                    <InfoRow label="Survey Type" value={deal.surveyType} />
                    <InfoRow label="Surveyed Date" value={formatDate(deal.surveyedDate)} />
                    <InfoRow label="Confirmed Survey Date" value={formatDate(deal.confirmedSurveyDate)} />
                    <InfoRow label="Confirmed Survey Time" value={deal.confirmedSurveyTime} />
                  </div>
                </div>

                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-4">Project Timeline</h3>
                  <MilestoneTimeline deal={deal} />
                </div>
              </div>

              {/* ── Works ── */}
              <div
                data-testid="drawer-tab-panel-works"
                className={`px-6 py-5 space-y-6 ${activeTab === "works" ? "block" : "hidden"}`}
              >
                <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={userCapability.includes("approver")}
                    />
                  </div>
                  <div className="divide-y divide-gray-50 mt-3">
                    <InfoRow label="Installed" value={deal.actualMeasuresInstalled} />
                    <InfoRow label="Lodgement Status" value={deal.lodgementStatus} />
                  </div>
                  <div className="mt-3">
                    <InstructMeasureEditor
                      dealId={deal.dealId}
                      portfolioId={portfolioId}
                      proposedMeasures={parseMeasures(deal.proposedMeasures ?? null)}
                      canEdit={userCapability.includes("approver")}
                      outOfOrderWarning={outOfOrderInstructionWarning(deal)}
                    />
                  </div>
                </div>

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

                <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
                data-testid="drawer-tab-panel-pibi-surveys"
                className={`px-6 py-5 space-y-6 ${activeTab === "pibi-surveys" ? "block" : "hidden"}`}
              >
                <PibiSurveysTabContent
                  deal={deal}
                  portfolioId={portfolioId}
                  userRole={userRole}
                  userCapability={userCapability}
                />
              </div>

            </div>

            {/* ── Footer ──────────────────────────────────────────────── */}
            <div className="shrink-0 px-6 py-4 border-t border-gray-100 bg-gray-50/50">
              {deal.uprn && (
                <p className="text-xs text-gray-400 font-mono">UPRN: {deal.uprn}</p>
              )}
            </div>
          </>
        )}
      </DrawerContent>
    </Drawer>
  );
}
