"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { markPropertySoldAction } from "@/app/actions/deal.actions";
import { ShieldCheck, CheckCircle2, AlertCircle, UploadCloud, Users, FileText } from "lucide-react";

interface MarkSoldModalProps {
  isOpen: boolean;
  onClose: () => void;
  property: {
    id: string;
    title: string;
    reference_code: string;
    price: number;
    listing_type: string;
  };
  leads?: Array<{ id: string; user_id?: string | null; full_name: string; email: string }>;
  onSuccess?: () => void;
}

export function MarkSoldModal({
  isOpen,
  onClose,
  property,
  leads = [],
  onSuccess,
}: MarkSoldModalProps) {
  const [dealSource, setDealSource] = React.useState<"PLATFORM_LEAD" | "OFF_PLATFORM">("PLATFORM_LEAD");
  const [selectedLeadId, setSelectedLeadId] = React.useState<string>("");
  const [finalPrice, setFinalPrice] = React.useState<string>(property.price ? String(property.price) : "");
  const [proofUrl, setProofUrl] = React.useState<string>("");
  const [proofType, setProofType] = React.useState<string>("DEED_OF_ASSIGNMENT");
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
  const [isDone, setIsDone] = React.useState(false);

  const isRental = property.listing_type === "FOR_RENT" || property.listing_type === "SHORTLET";

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage(null);
    setIsSubmitting(true);

    try {
      let buyerUserId: string | null = null;
      let leadId: string | null = null;

      if (dealSource === "PLATFORM_LEAD" && selectedLeadId) {
        const lead = leads.find((l) => l.id === selectedLeadId);
        leadId = selectedLeadId;
        buyerUserId = lead?.user_id || null;
      }

      const res = await markPropertySoldAction({
        propertyId: property.id,
        transactionType: isRental ? "RENTAL" : "SALE",
        finalPrice: finalPrice ? Number(finalPrice) : property.price,
        currency: "NGN",
        buyerUserId,
        leadId,
        proofDocumentUrl: dealSource === "OFF_PLATFORM" && proofUrl.trim() ? proofUrl.trim() : null,
        proofDocumentType: dealSource === "OFF_PLATFORM" ? (proofType as any) : null,
      });

      if (!res.success) {
        setErrorMessage(res.error || "Failed to record transaction");
        setIsSubmitting(false);
        return;
      }

      setIsDone(true);
      if (onSuccess) onSuccess();
      setTimeout(() => {
        setIsDone(false);
        onClose();
      }, 1800);
    } catch (err: any) {
      setErrorMessage(err.message || "An unexpected error occurred");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="max-w-lg p-6 sm:p-7 rounded-2xl">
        <DialogHeader className="space-y-1">
          <DialogTitle className="text-xl font-bold text-foreground">
            Mark Property as {isRental ? "Rented / Leased" : "Sold / Closed"}
          </DialogTitle>
          <DialogDescription className="text-xs text-muted-foreground">
            Closing deals with verified buyer handshake boosts your Verified Realtor reputation and closed track record.
          </DialogDescription>
        </DialogHeader>

        {isDone ? (
          <div className="py-12 text-center space-y-3">
            <div className="size-14 rounded-full bg-emerald-500/15 text-emerald-600 flex items-center justify-center mx-auto">
              <CheckCircle2 className="size-8" />
            </div>
            <h3 className="font-bold text-lg text-foreground">Deal Recorded Successfully!</h3>
            <p className="text-xs text-muted-foreground max-w-xs mx-auto">
              {dealSource === "PLATFORM_LEAD"
                ? "A verification confirmation has been sent to the buyer."
                : "Transaction recorded and queued for track record verification."}
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-5 pt-2">
            {errorMessage && (
              <div className="p-3 rounded-xl bg-destructive/10 border border-destructive/20 text-xs text-destructive flex items-center gap-2">
                <AlertCircle className="size-4 shrink-0" />
                <span>{errorMessage}</span>
              </div>
            )}

            {/* Property Summary Pill */}
            <div className="p-3 rounded-xl bg-muted/40 border border-border text-xs flex items-center justify-between">
              <span className="font-bold text-foreground truncate">{property.title}</span>
              <span className="font-mono text-muted-foreground shrink-0">{property.reference_code}</span>
            </div>

            {/* 1. Select Deal Source */}
            <div className="space-y-2">
              <Label className="text-xs font-bold text-foreground">
                How was this deal closed? *
              </Label>
              <div className="grid grid-cols-2 gap-3">
                <button
                  type="button"
                  onClick={() => setDealSource("PLATFORM_LEAD")}
                  className={`p-3 rounded-xl border text-left space-y-1 transition-all cursor-pointer ${
                    dealSource === "PLATFORM_LEAD"
                      ? "border-emerald-600 bg-emerald-500/10 ring-1 ring-emerald-600 text-foreground"
                      : "border-border bg-card text-muted-foreground hover:bg-muted/50"
                  }`}
                >
                  <div className="flex items-center gap-1.5 font-bold text-xs text-foreground">
                    <Users className="size-3.5 text-emerald-600" />
                    <span>Platform Inquiry / Lead</span>
                  </div>
                  <p className="text-[11px] leading-tight">
                    Dual-sided handshake with registered buyer (Instant 5x Verified Badge).
                  </p>
                </button>

                <button
                  type="button"
                  onClick={() => setDealSource("OFF_PLATFORM")}
                  className={`p-3 rounded-xl border text-left space-y-1 transition-all cursor-pointer ${
                    dealSource === "OFF_PLATFORM"
                      ? "border-emerald-600 bg-emerald-500/10 ring-1 ring-emerald-600 text-foreground"
                      : "border-border bg-card text-muted-foreground hover:bg-muted/50"
                  }`}
                >
                  <div className="flex items-center gap-1.5 font-bold text-xs text-foreground">
                    <FileText className="size-3.5 text-emerald-600" />
                    <span>Walk-In / Offline Client</span>
                  </div>
                  <p className="text-[11px] leading-tight">
                    Upload receipt or deed proof for compliance desk audit.
                  </p>
                </button>
              </div>
            </div>

            {/* 2. Platform Lead Selection */}
            {dealSource === "PLATFORM_LEAD" && (
              <div className="space-y-1.5">
                <Label htmlFor="buyerLead" className="text-xs font-bold text-foreground">
                  Select Registered Buyer / Lead *
                </Label>
                {leads.length > 0 ? (
                  <Select value={selectedLeadId} onValueChange={(val) => setSelectedLeadId(val || "")}>
                    <SelectTrigger id="buyerLead" className="text-xs h-10 rounded-xl">
                      <SelectValue placeholder="Choose buyer from leads list..." />
                    </SelectTrigger>
                    <SelectContent>
                      {leads.map((l) => (
                        <SelectItem key={l.id} value={l.id}>
                          {l.full_name} ({l.email})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                ) : (
                  <div className="p-3 rounded-xl bg-muted/40 border border-border text-xs text-muted-foreground">
                    No CRM leads found for this listing yet. If this was an external client, select &apos;Walk-In / Offline Client&apos;.
                  </div>
                )}
              </div>
            )}

            {/* 3. Off-Platform Proof Option */}
            {dealSource === "OFF_PLATFORM" && (
              <div className="space-y-3 p-3.5 rounded-xl bg-muted/30 border border-border">
                <div className="space-y-1.5">
                  <Label className="text-xs font-bold text-foreground">Proof Document Type</Label>
                  <Select value={proofType} onValueChange={(val) => setProofType(val || "DEED_OF_ASSIGNMENT")}>
                    <SelectTrigger className="text-xs h-9 rounded-xl">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="DEED_OF_ASSIGNMENT">Deed of Assignment (Signed Page)</SelectItem>
                      <SelectItem value="RENT_RECEIPT">Stamped Rent / Caution Fee Receipt</SelectItem>
                      <SelectItem value="ALLOCATION_LETTER">Letter of Allocation / Developer Contract</SelectItem>
                      <SelectItem value="CONTRACT_OF_SALE">Contract of Sale</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label htmlFor="proofUrl" className="text-xs font-bold text-foreground">
                    Proof Document Secure URL (Optional for Staff Audit)
                  </Label>
                  <Input
                    id="proofUrl"
                    value={proofUrl}
                    onChange={(e) => setProofUrl(e.target.value)}
                    placeholder="https://... (GCS or Supabase secure document link)"
                    className="text-xs h-9 rounded-xl"
                  />
                  <p className="text-[10px] text-muted-foreground">
                    Staff will inspect this document to award the <strong>Staff Verified Closed Deal</strong> badge.
                  </p>
                </div>
              </div>
            )}

            {/* 4. Final Deal Price */}
            <div className="space-y-1.5">
              <Label htmlFor="finalPrice" className="text-xs font-bold text-foreground">
                Final Agreed Deal Price (NGN)
              </Label>
              <Input
                id="finalPrice"
                type="number"
                value={finalPrice}
                onChange={(e) => setFinalPrice(e.target.value)}
                placeholder="e.g. 240000000"
                className="text-xs h-10 rounded-xl font-mono"
              />
            </div>

            {/* Integrity Warning */}
            <div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-[11px] text-amber-900 dark:text-amber-200 flex items-start gap-2">
              <ShieldCheck className="size-4 text-amber-600 shrink-0 mt-0.5" />
              <span>
                Fabricating closed deals or ghost transactions violates Nigeria Listing Marketplace policies and will lead to immediate loss of Verified Realtor status and LASRERA reporting.
              </span>
            </div>

            {/* Modal Actions */}
            <div className="flex items-center justify-end gap-2.5 pt-2">
              <Button
                type="button"
                variant="outline"
                onClick={onClose}
                disabled={isSubmitting}
                className="text-xs h-10 px-4 rounded-xl"
              >
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting}
                className="text-xs h-10 px-5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl shadow-sm"
              >
                {isSubmitting ? "Recording Deal..." : "Confirm & Mark Closed"}
              </Button>
            </div>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
}
