"use client";

import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { X, CheckCircle2, Circle, AlertTriangle, ChevronRight, ChevronDown, Trash2, RotateCcw } from "lucide-react";
import {
  Drawer,
  DrawerClose,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
} from "@/app/shadcn_components/ui/drawer";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/app/shadcn_components/ui/tooltip";
import { STAGE_COLORS } from "./types";
import type { ClassifiedDeal, PortfolioCapabilityType, RemovalRequest } from "./types";

// -----------------------------------------------------------------------
// Removal request section
// -----------------------------------------------------------------------
const WRITE_ROLES = ["creator", "admin", "write"];

function RemovalRequestSection({
  dealId,
  portfolioId,
  userRole,
  userCapability,
}: {
  dealId: string;
  portfolioId: string;
  userRole: string;
  userCapability: PortfolioCapabilityType;
}) {
  const queryClient = useQueryClient();
  const [dialogType, setDialogType] = useState<"removal" | "re_addition" | null>(null);
  const [reason, setReason] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [reviewing, setReviewing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const canRequest = WRITE_ROLES.includes(userRole);
  const isApprover = userCapability.includes("approver");

  const { data, isLoading } = useQuery<{ requests: RemovalRequest[] }>({
    queryKey: ["removalRequests", portfolioId, dealId],
    queryFn: async () => {
      const res = await fetch(
        `/api/portfolio/${portfolioId}/removal-requests?dealId=${dealId}`,
      );
      if (!res.ok) throw new Error("Failed to fetch removal requests");
      return res.json();
    },
    staleTime: 30_000,
  });

  const latest = data?.requests?.[0] ?? null;

  // Derive effective state from the most recent request
  type EffectiveState = "active" | "pending_removal" | "removed" | "pending_re_addition";
  const effectiveState: EffectiveState = (() => {
    if (!latest) return "active";
    if (latest.status === "pending") {
      return latest.type === "re_addition" ? "pending_re_addition" : "pending_removal";
    }
    if (latest.type === "removal" && latest.status === "approved") return "removed";
    if (latest.type === "re_addition" && latest.status === "declined") return "removed";
    return "active";
  })();

  const pendingRequest = latest?.status === "pending" ? latest : null;
  const latestResolvedRequest = latest?.status !== "pending" ? latest : null;

  function closeDialog() {
    setDialogType(null);
    setReason("");
    setError(null);
  }

  async function handleSubmit() {
    if (!reason.trim() || !dialogType) return;
    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch(`/api/portfolio/${portfolioId}/removal-requests`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ hubspotDealId: dealId, reason: reason.trim(), type: dialogType }),
      });
      if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        setError(json.error ?? "Failed to submit request");
        return;
      }
      closeDialog();
      queryClient.invalidateQueries({ queryKey: ["removalRequests", portfolioId, dealId] });
    } finally {
      setSubmitting(false);
    }
  }

  async function handleReview(requestId: string, action: "approved" | "declined") {
    setReviewing(true);
    setError(null);
    try {
      const res = await fetch(`/api/portfolio/${portfolioId}/removal-requests`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ requestId: Number(requestId), action }),
      });
      if (!res.ok) {
        const json = await res.json().catch(() => ({}));
        setError(json.error ?? "Failed to review request");
        return;
      }
      queryClient.invalidateQueries({ queryKey: ["removalRequests", portfolioId, dealId] });
    } finally {
      setReviewing(false);
    }
  }

  function resolvedLabel(req: RemovalRequest): string {
    if (req.type === "re_addition") {
      return req.status === "approved" ? "Re-addition Approved" : "Re-addition Declined";
    }
    return req.status === "approved" ? "Removal Approved" : "Removal Declined";
  }

  if (isLoading) {
    return <p className="text-xs text-gray-400 py-2">Loading…</p>;
  }

  return (
    <div className="space-y-3">
      {error && (
        <p className="text-xs text-red-600 bg-red-50 px-3 py-2 rounded-lg">{error}</p>
      )}

      {/* Pending request — visible to everyone */}
      {pendingRequest && (
        <div className="rounded-xl border border-amber-200 bg-amber-50 p-3.5 space-y-2">
          <div className="flex items-center gap-2">
            <span className="text-xs font-semibold text-amber-700 bg-amber-100 px-2 py-0.5 rounded-full border border-amber-200">
              {pendingRequest.type === "re_addition" ? "Pending Re-addition Request" : "Pending Removal Request"}
            </span>
          </div>
          <p className="text-xs text-gray-700 leading-relaxed">{pendingRequest.reason}</p>
          <p className="text-[11px] text-gray-400">
            Requested by <span className="font-medium text-gray-600">{pendingRequest.requestedByEmail}</span>
            {" · "}
            {formatDateTime(pendingRequest.requestedAt)}
          </p>
          {isApprover && (
            <div className="flex gap-2 pt-1">
              <button
                onClick={() => handleReview(pendingRequest.id, "approved")}
                disabled={reviewing}
                className="flex-1 text-xs font-medium px-3 py-1.5 rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50 transition-colors"
              >
                {pendingRequest.type === "re_addition" ? "Approve Re-addition" : "Approve Removal"}
              </button>
              <button
                onClick={() => handleReview(pendingRequest.id, "declined")}
                disabled={reviewing}
                className="flex-1 text-xs font-medium px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-100 disabled:opacity-50 transition-colors"
              >
                Decline
              </button>
            </div>
          )}
        </div>
      )}

      {/* Most recent resolved request */}
      {latestResolvedRequest && (
        <div className={`rounded-xl border p-3.5 space-y-1.5 ${
          latestResolvedRequest.status === "approved"
            ? "border-emerald-200 bg-emerald-50"
            : "border-gray-200 bg-gray-50"
        }`}>
          <div className="flex items-center gap-2">
            <span className={`text-xs font-semibold px-2 py-0.5 rounded-full border ${
              latestResolvedRequest.status === "approved"
                ? "text-emerald-700 bg-emerald-100 border-emerald-200"
                : "text-gray-600 bg-gray-100 border-gray-200"
            }`}>
              {resolvedLabel(latestResolvedRequest)}
            </span>
          </div>
          <p className="text-xs text-gray-600 leading-relaxed">{latestResolvedRequest.reason}</p>
          <p className="text-[11px] text-gray-400">
            Requested by <span className="font-medium text-gray-600">{latestResolvedRequest.requestedByEmail}</span>
            {" · "}
            {formatDateTime(latestResolvedRequest.requestedAt)}
          </p>
          {latestResolvedRequest.reviewedByEmail && (
            <p className="text-[11px] text-gray-400">
              {latestResolvedRequest.status === "approved" ? "Approved" : "Declined"} by{" "}
              <span className="font-medium text-gray-600">{latestResolvedRequest.reviewedByEmail}</span>
              {latestResolvedRequest.reviewedAt && ` · ${formatDateTime(latestResolvedRequest.reviewedAt)}`}
            </p>
          )}
        </div>
      )}

      {/* Action buttons — shown when no pending request */}
      {!pendingRequest && (
        <>
          {effectiveState === "active" && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-block w-full">
                    <button
                      onClick={() => { if (canRequest) setDialogType("removal"); }}
                      disabled={!canRequest}
                      className={`w-full flex items-center justify-center gap-2 text-xs font-medium px-3 py-2 rounded-lg border transition-colors ${
                        canRequest
                          ? "border-red-200 text-red-600 hover:bg-red-50 bg-white"
                          : "border-gray-100 text-gray-300 bg-gray-50 cursor-not-allowed"
                      }`}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                      Request Removal from Project
                    </button>
                  </span>
                </TooltipTrigger>
                {!canRequest && (
                  <TooltipContent side="top" className="text-xs">
                    Not available with read-only permissions
                  </TooltipContent>
                )}
              </Tooltip>
            </TooltipProvider>
          )}

          {effectiveState === "removed" && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-block w-full">
                    <button
                      onClick={() => { if (canRequest) setDialogType("re_addition"); }}
                      disabled={!canRequest}
                      className={`w-full flex items-center justify-center gap-2 text-xs font-medium px-3 py-2 rounded-lg border transition-colors ${
                        canRequest
                          ? "border-blue-200 text-blue-600 hover:bg-blue-50 bg-white"
                          : "border-gray-100 text-gray-300 bg-gray-50 cursor-not-allowed"
                      }`}
                    >
                      <RotateCcw className="h-3.5 w-3.5" />
                      Request Re-addition to Project
                    </button>
                  </span>
                </TooltipTrigger>
                {!canRequest && (
                  <TooltipContent side="top" className="text-xs">
                    Not available with read-only permissions
                  </TooltipContent>
                )}
              </Tooltip>
            </TooltipProvider>
          )}
        </>
      )}

      {/* Shared dialog for removal and re-addition requests */}
      <Dialog open={dialogType !== null} onOpenChange={(v) => { if (!v) closeDialog(); }}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="text-base font-semibold text-gray-800">
              {dialogType === "re_addition" ? "Request Re-addition to Project" : "Request Removal from Project"}
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <p className="text-xs text-gray-500 leading-relaxed">
              {dialogType === "re_addition"
                ? "Please provide a reason why this property should be re-added to the project. This will be recorded for audit purposes."
                : "Please provide a reason why this property should be removed from the project. This will be recorded for audit purposes."}
            </p>
            <textarea
              className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-200 focus:border-blue-300 resize-none"
              placeholder={dialogType === "re_addition" ? "Reason for re-addition…" : "Reason for removal…"}
              rows={4}
              value={reason}
              onChange={(e) => setReason(e.target.value)}
            />
            {error && <p className="text-xs text-red-600">{error}</p>}
          </div>
          <DialogFooter className="gap-2">
            <button
              onClick={closeDialog}
              className="text-xs font-medium px-4 py-2 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit}
              disabled={!reason.trim() || submitting}
              className={`text-xs font-medium px-4 py-2 rounded-lg text-white disabled:opacity-50 transition-colors ${
                dialogType === "re_addition"
                  ? "bg-blue-600 hover:bg-blue-700"
                  : "bg-red-600 hover:bg-red-700"
              }`}
            >
              {submitting ? "Submitting…" : "Submit Request"}
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

// -----------------------------------------------------------------------
// Approval log placeholder (expand into a real implementation as needed)
// -----------------------------------------------------------------------
function ApprovalLogSection({ dealId, portfolioId }: { dealId: string; portfolioId: string }) {
  void dealId; void portfolioId;
  return <p className="text-xs text-gray-400">No approvals recorded.</p>;
}

function formatDateTime(d: string | Date | null | undefined): string {
  if (!d) return "";
  try {
    return new Date(d).toLocaleString("en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch { return ""; }
}

// -----------------------------------------------------------------------
// Milestone definitions — ordered pipeline steps with their date fields
// -----------------------------------------------------------------------
const MILESTONES: { label: string; field: keyof ClassifiedDeal; sublabel?: string }[] = [
  { label: "Booking Confirmed",    field: "confirmedSurveyDate" },
  { label: "Assessment Completed", field: "surveyedDate" },
  { label: "Coordination (V1)",    field: "ioeV1Date",            sublabel: "IOE/MTP V1" },
  { label: "Coordination (V2)",    field: "ioeV2Date",            sublabel: "IOE/MTP V2" },
  { label: "Design Completed",     field: "designDate" },
  { label: "Measures Lodged",      field: "measuresLodgementDate" },
  { label: "Stage 1 Lodgement",    field: "fullLodgementDate" },
];

function formatDate(d: Date | string | null | undefined): string | null {
  if (!d) return null;
  try {
    return new Date(d).toLocaleDateString("en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return null;
  }
}

// -----------------------------------------------------------------------
// Mini info row
// -----------------------------------------------------------------------
function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  if (!value) return null;
  return (
    <div className="flex items-start gap-3 py-2 border-b border-gray-50 last:border-0">
      <span className="text-xs text-gray-400 font-medium w-32 shrink-0 pt-0.5">{label}</span>
      <span className="text-xs text-gray-700 flex-1 leading-relaxed">{value}</span>
    </div>
  );
}

// -----------------------------------------------------------------------
// Stage badge
// -----------------------------------------------------------------------
function StageBadge({ stage }: { stage: ClassifiedDeal["displayStage"] }) {
  const c = STAGE_COLORS[stage] ?? STAGE_COLORS["Unknown Stage"];
  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold border ${c.bg} ${c.text} ${c.border}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${c.dot}`} />
      {stage}
    </span>
  );
}

// -----------------------------------------------------------------------
// Vertical milestone timeline
// -----------------------------------------------------------------------
function MilestoneTimeline({ deal }: { deal: ClassifiedDeal }) {
  const milestones = MILESTONES.map((m) => ({
    ...m,
    date: formatDate(deal[m.field] as Date | string | null),
  }));

  // Find last completed index
  const lastCompletedIdx = milestones.reduce((acc, m, i) => (m.date ? i : acc), -1);

  return (
    <div className="relative">
      {milestones.map((m, i) => {
        const completed = !!m.date;
        const isLast = i === milestones.length - 1;

        return (
          <div key={m.field} className="flex items-stretch gap-3">
            {/* Left: dot + connecting line */}
            <div className="flex flex-col items-center w-5 shrink-0">
              <div className={`relative z-10 flex items-center justify-center w-5 h-5 rounded-full border-2 mt-0.5 transition-all duration-300 ${
                completed
                  ? "bg-brandmidblue border-brandmidblue"
                  : i <= lastCompletedIdx + 1
                    ? "bg-white border-brandblue/30"
                    : "bg-white border-gray-200"
              }`}>
                {completed ? (
                  <CheckCircle2 className="h-3 w-3 text-white" />
                ) : (
                  <Circle className={`h-2 w-2 ${i <= lastCompletedIdx + 1 ? "text-brandblue/40" : "text-gray-300"}`} />
                )}
              </div>
              {!isLast && (
                <div className={`w-0.5 flex-1 my-0.5 ${
                  completed && milestones[i + 1]?.date ? "bg-brandmidblue/40" : "bg-gray-100"
                }`} />
              )}
            </div>

            {/* Right: label + date */}
            <div className={`pb-4 flex-1 min-w-0 ${isLast ? "pb-0" : ""}`}>
              <div className="flex items-start justify-between gap-2">
                <div>
                  <p className={`text-xs font-semibold leading-tight ${
                    completed ? "text-gray-800" : "text-gray-400"
                  }`}>
                    {m.label}
                  </p>
                  {m.sublabel && (
                    <p className="text-[10px] text-gray-400 mt-0.5">{m.sublabel}</p>
                  )}
                </div>
                {m.date ? (
                  <span className="text-[11px] font-medium text-brandmidblue bg-brandlightblue/60 px-2 py-0.5 rounded-full shrink-0 whitespace-nowrap">
                    {m.date}
                  </span>
                ) : (
                  <span className="text-[11px] text-gray-300 shrink-0">Pending</span>
                )}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// -----------------------------------------------------------------------
// PropertyDetailDrawer — main component
// -----------------------------------------------------------------------
interface PropertyDetailDrawerProps {
  deal: ClassifiedDeal | null;
  onClose: () => void;
  portfolioId: string;
  userRole: string;
  userCapability: PortfolioCapabilityType;
  userEmail: string;
}

export default function PropertyDetailDrawer({
  deal,
  portfolioId,
  onClose,
  userRole,
  userCapability,
}: PropertyDetailDrawerProps) {
  const open = !!deal;
  const [isLogOpen, setIsLogOpen] = useState(false);

  return (
    <Drawer open={open} onOpenChange={(v) => !v && onClose()} direction="right">
      <DrawerContent className="fixed right-0 top-0 bottom-0 h-full w-[42vw] min-w-80 max-w-lg 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-4 border-b border-gray-100">
              <div className="flex items-start justify-between gap-3">
                <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>

            </DrawerHeader>

            {/* Scrollable body */}
            <div className="flex-1 overflow-y-auto px-6 py-5 space-y-6">

              {/* Damp & mould alert */}
              {(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>
              )}

              {/* Key details */}
              <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
                        ? <span className={`font-semibold px-1.5 py-0.5 rounded text-xs ${
                            Number(deal.preSapScore) < 30
                              ? "text-red-600 bg-red-50"
                              : Number(deal.preSapScore) < 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>

              {/* Measures */}
              {(deal.proposedMeasures || deal.approvedPackage || deal.actualMeasuresInstalled) && (
                <div>
                  <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">Measures</h3>
                  <div className="divide-y divide-gray-50">
                    <InfoRow label="Proposed" value={deal.proposedMeasures} />
                    <InfoRow label="Approved Package" value={deal.approvedPackage} />
                    <InfoRow label="Installed" value={deal.actualMeasuresInstalled} />
                    <InfoRow label="Lodgement Status" value={deal.lodgementStatus} />
                  </div>
                </div>
              )}

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

              {/* Removal request */}
              <div className="border-t border-gray-100 pt-4">
                <h3 className="text-xs font-bold uppercase tracking-wider text-gray-400 mb-3">
                  Project Removal
                </h3>
                <RemovalRequestSection
                  dealId={deal.dealId}
                  portfolioId={portfolioId}
                  userRole={userRole}
                  userCapability={userCapability}
                />
              </div>

              {/* Approval log — collapsible */}
              <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">
                    <ApprovalLogSection dealId={deal.dealId} portfolioId={portfolioId} />
                  </div>
                )}
              </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>
  );
}
