"use client";

import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Trash2, RotateCcw } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/app/shadcn_components/ui/dialog";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/app/shadcn_components/ui/tooltip";
import type { PortfolioCapabilityType, RemovalRequest } from "../types";
import { WRITE_ROLES, formatDateTime } from "./primitives";

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

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

      {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>
      )}

      {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>
      )}

      {!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>
          )}
        </>
      )}

      <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>
  );
}
