"use client";

import * as React from "react";
import { PropertyTransactionRow } from "@/types/database";
import { ShieldCheck, CheckCircle2, AlertTriangle, Phone } from "lucide-react";
import { MdCorporateFare } from "react-icons/md";
import { Button } from "@/components/ui/button";
import { formatNaira } from "@/lib/utils";
import { confirmBuyerDealAction } from "@/app/actions/deal.actions";
import { WriteReviewModal } from "@/components/reviews/write-review-modal";

interface BuyerDealConfirmationCardProps {
  transaction: PropertyTransactionRow & {
    property?: { title: string; slug: string; reference_code: string; price: number; street_address?: string };
    agent?: { id: string; first_name: string | null; last_name: string | null; avatar_url: string | null; phone_number: string | null };
  };
  onResolved?: () => void;
}

export function BuyerDealConfirmationCard({
  transaction,
  onResolved,
}: BuyerDealConfirmationCardProps) {
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [status, setStatus] = React.useState(transaction.verification_status);
  const [isReviewOpen, setIsReviewOpen] = React.useState(false);

  const agentName = transaction.agent
    ? `${transaction.agent.first_name || ""} ${transaction.agent.last_name || ""}`.trim()
    : "Your Realtor";

  const handleConfirm = async () => {
    if (isSubmitting || !transaction.buyer_confirmation_token) return;
    setIsSubmitting(true);

    const res = await confirmBuyerDealAction({
      transactionId: transaction.id,
      confirmationToken: transaction.buyer_confirmation_token,
      action: "CONFIRM",
    });

    if (res.success) {
      setStatus("VERIFIED_PLATFORM_DEAL");
      setIsReviewOpen(true);
      if (onResolved) onResolved();
    }
    setIsSubmitting(false);
  };

  const handleDispute = async () => {
    if (isSubmitting || !transaction.buyer_confirmation_token) return;
    const reason = window.prompt("Please briefly describe why this deal record is incorrect:");
    if (reason === null) return; // cancelled

    setIsSubmitting(true);
    const res = await confirmBuyerDealAction({
      transactionId: transaction.id,
      confirmationToken: transaction.buyer_confirmation_token,
      action: "DISPUTE",
      disputeReason: reason,
    });

    if (res.success) {
      setStatus("DISPUTED_OR_FLAGGED");
      if (onResolved) onResolved();
    }
    setIsSubmitting(false);
  };

  if (status !== "PENDING_BUYER_CONFIRMATION") {
    return null;
  }

  return (
    <div className="p-5 sm:p-6 rounded-2xl border-2 border-amber-500/40 bg-gradient-to-br from-amber-500/10 via-card to-emerald-500/5 shadow-md space-y-4">
      {/* Alert Header */}
      <div className="flex items-start gap-3">
        <div className="size-10 rounded-xl bg-amber-500/20 text-amber-700 dark:text-amber-400 flex items-center justify-center shrink-0">
          <ShieldCheck className="size-6" />
        </div>
        <div>
          <h4 className="font-bold text-base text-foreground">
            Confirm your property deal
          </h4>
          <p className="text-xs text-muted-foreground mt-0.5">
            <strong className="text-foreground">{agentName}</strong> reported closing this deal with you:
          </p>
        </div>
      </div>

      {/* Property Details Snapshot */}
      <div className="p-3.5 rounded-xl bg-card border border-border flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs">
        <div className="flex items-center gap-2.5 min-w-0">
          <MdCorporateFare className="size-4 text-emerald-600 shrink-0" />
          <div className="min-w-0">
            <p className="font-bold text-foreground truncate">
              {transaction.property?.title || "Property Listing"}
            </p>
            <p className="text-[11px] text-muted-foreground">
              Ref: <span className="font-mono">{transaction.property?.reference_code || "N/A"}</span>
              {transaction.property?.street_address && ` · ${transaction.property.street_address}`}
            </p>
          </div>
        </div>

        <div className="text-right shrink-0">
          <p className="font-black text-sm text-foreground">
            {formatNaira(transaction.final_price || transaction.property?.price || 0)}
          </p>
          <span className="text-[10px] text-muted-foreground uppercase font-semibold">
            {transaction.transaction_type}
          </span>
        </div>
      </div>

      {/* Action Buttons */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pt-1">
        <p className="text-[11px] text-muted-foreground flex items-center gap-1">
          <ShieldCheck className="size-3.5 text-emerald-600 shrink-0" />
          <span>Confirming lets you leave a verified review for this agent.</span>
        </p>

        <div className="flex items-center gap-2">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={handleDispute}
            disabled={isSubmitting}
            className="text-xs h-9 border-destructive/30 text-destructive hover:bg-destructive/10"
          >
            Not my deal
          </Button>

          <Button
            type="button"
            size="sm"
            onClick={handleConfirm}
            disabled={isSubmitting}
            className="text-xs h-9 bg-emerald-600 hover:bg-emerald-700 text-white font-bold gap-1.5 shadow-sm"
          >
            <CheckCircle2 className="size-3.5" />
            <span>Confirm &amp; Review</span>
          </Button>
        </div>
      </div>

      {/* Trigger Review Modal after confirmation */}
      {transaction.agent?.id && (
        <WriteReviewModal
          isOpen={isReviewOpen}
          onClose={() => setIsReviewOpen(false)}
          targetType="AGENT"
          targetId={transaction.agent.id}
          targetName={agentName}
          propertyId={transaction.property_id}
        />
      )}
    </div>
  );
}
