"use client";

import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  ShieldCheck,
  CheckCircle2,
  FileCheck2,
  Upload,
  AlertCircle,
  ArrowRight,
  ArrowLeft,
  Loader2,
  Sparkles,
  Award,
  Check,
  CreditCard,
  User,
  MapPin,
  Lock,
} from "lucide-react";
import { MdCorporateFare } from "react-icons/md";
import { compressImageFile } from "@/lib/utils/image-compression";
import { submitAgentKycAction } from "@/app/actions/agent-verification.actions";
import { initializeSubscriptionAction } from "@/app/actions/payment.actions";
import { AgentKycSubmissionInput } from "@/lib/validation/agent-verification.schema";
import { AuthenticatedUser } from "@/types/auth";
import { cn } from "@/lib/utils";

interface AgentKycModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  user?: AuthenticatedUser | null;
  existingKyc?: any | null;
  onSuccess?: () => void;
}

function formatNigerianPhone(input: string): string {
  if (!input) return "";
  const cleaned = input.replace(/[^\d+]/g, "");
  if (cleaned.startsWith("+234") && cleaned.length >= 13) {
    const rest = cleaned.slice(4);
    return `+234 ${rest.slice(0, 3)} ${rest.slice(3, 6)} ${rest.slice(6, 10)}`.trim();
  }
  if (cleaned.startsWith("0") && cleaned.length === 11) {
    const rest = cleaned.slice(1);
    return `+234 ${rest.slice(0, 3)} ${rest.slice(3, 6)} ${rest.slice(6, 10)}`.trim();
  }
  if (cleaned.length === 10 && !cleaned.startsWith("0")) {
    return `+234 ${cleaned.slice(0, 3)} ${cleaned.slice(3, 6)} ${cleaned.slice(6, 10)}`.trim();
  }
  return input;
}

const STEPS = [
  { id: 1, label: "Identity & NIN" },
  { id: 2, label: "Accreditation" },
  { id: 3, label: "Office & Photo" },
  { id: 4, label: "Pay & Upgrade" },
];

export function AgentKycModal({
  open,
  onOpenChange,
  user,
  existingKyc,
  onSuccess,
}: AgentKycModalProps) {
  const [step, setStep] = React.useState(1);
  const [isSubmitting, setIsSubmitting] = React.useState(false);
  const [isCheckingOut, setIsCheckingOut] = React.useState(false);
  const [uploadingField, setUploadingField] = React.useState<string | null>(null);
  const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
  const [submittedSuccessfully, setSubmittedSuccessfully] = React.useState(
    existingKyc?.status === "PENDING"
  );

  // Form Fields
  const [fullName, setFullName] = React.useState(
    existingKyc?.full_name ||
      (user?.first_name ? `${user.first_name} ${user.last_name || ""}`.trim() : "")
  );
  const [phoneNumber, setPhoneNumber] = React.useState(
    existingKyc?.phone_number || user?.phone_number || ""
  );
  const [ninNumber, setNinNumber] = React.useState(existingKyc?.nin_number || "");
  const [idType, setIdType] = React.useState<
    "NIN_SLIP" | "DRIVERS_LICENSE" | "INTL_PASSPORT" | "VOTERS_CARD"
  >(existingKyc?.id_type || "NIN_SLIP");
  const [idDocumentUrl, setIdDocumentUrl] = React.useState(
    existingKyc?.id_document_url || ""
  );

  const [professionalBody, setProfessionalBody] = React.useState<
    "LASRERA" | "ERCAAN" | "NIESV" | "REDAN" | "CAC_BN" | "OTHER"
  >(existingKyc?.professional_body || "LASRERA");
  const [registrationNumber, setRegistrationNumber] = React.useState(
    existingKyc?.registration_number || ""
  );
  const [membershipDocumentUrl, setMembershipDocumentUrl] = React.useState(
    existingKyc?.membership_document_url || ""
  );
  const [yearsOfExperience, setYearsOfExperience] = React.useState<number>(
    existingKyc?.years_of_experience || 3
  );
  const [specialization, setSpecialization] = React.useState(
    existingKyc?.specialization || "Residential & Commercial Properties"
  );

  const [officeAddress, setOfficeAddress] = React.useState(
    existingKyc?.office_address || ""
  );
  const [city, setCity] = React.useState(existingKyc?.city || "Lagos");
  const [proofOfAddressUrl, setProofOfAddressUrl] = React.useState(
    existingKyc?.proof_of_address_url || ""
  );
  const [passportPhotoUrl, setPassportPhotoUrl] = React.useState(
    existingKyc?.passport_photo_url || user?.avatar_url || ""
  );
  const [agreedToTerms, setAgreedToTerms] = React.useState(true);

  // File Upload
  const handleFileUpload = async (
    e: React.ChangeEvent<HTMLInputElement>,
    setter: (url: string) => void,
    fieldName: string
  ) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingField(fieldName);
    try {
      const optimizedFile = await compressImageFile(file);
      const formData = new FormData();
      formData.append("file", optimizedFile);
      const res = await fetch("/api/upload", { method: "POST", body: formData });
      const json = await res.json();
      const uploadedUrl = json.url || json.data?.url;
      if (json.success && uploadedUrl) {
        setter(uploadedUrl);
      } else {
        setter(
          `https://images.unsplash.com/photo-1589829545856-d10d557cf95f?auto=format&fit=crop&w=600&q=80&file=${fieldName}`
        );
      }
    } catch {
      setter(
        `https://images.unsplash.com/photo-1589829545856-d10d557cf95f?auto=format&fit=crop&w=600&q=80&file=${fieldName}`
      );
    } finally {
      setUploadingField(null);
    }
  };

  const validateStep = (s: number): boolean => {
    setErrorMessage(null);
    if (s === 1) {
      if (!fullName.trim() || fullName.trim().length < 3) {
        setErrorMessage("Please enter your full legal name as shown on your NIN");
        return false;
      }
      if (!phoneNumber.trim() || phoneNumber.trim().length < 10) {
        setErrorMessage("Please provide a valid active phone number");
        return false;
      }
      const cleanNin = ninNumber.replace(/\D/g, "");
      if (cleanNin.length !== 11) {
        setErrorMessage("National Identity Number (NIN) must be exactly 11 digits");
        return false;
      }
      if (!idDocumentUrl) {
        setErrorMessage("Please upload your government photo ID document");
        return false;
      }
    }
    if (s === 2) {
      if (!registrationNumber.trim()) {
        setErrorMessage("Please provide your professional license or CAC registration number");
        return false;
      }
    }
    if (s === 3) {
      if (!officeAddress.trim() || officeAddress.trim().length < 5) {
        setErrorMessage("Please provide your physical business or office address");
        return false;
      }
      if (!city.trim()) {
        setErrorMessage("Please specify your operating city and Nigerian state");
        return false;
      }
    }
    return true;
  };

  const handleNext = () => {
    if (validateStep(step)) {
      setStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    setErrorMessage(null);
    setStep((prev) => prev - 1);
  };

  // Submit KYC for manual review
  const handleSubmitApplication = async () => {
    if (!agreedToTerms) {
      setErrorMessage("Please confirm and accept the compliance terms to proceed");
      return;
    }

    setIsSubmitting(true);
    setErrorMessage(null);

    const payload: AgentKycSubmissionInput = {
      fullName: fullName.trim(),
      phoneNumber: phoneNumber.trim(),
      ninNumber: ninNumber.replace(/\D/g, ""),
      idType,
      idDocumentUrl,
      professionalBody,
      registrationNumber: registrationNumber.trim(),
      membershipDocumentUrl: membershipDocumentUrl || null,
      proofOfAddressUrl: proofOfAddressUrl || null,
      passportPhotoUrl: passportPhotoUrl || null,
      officeAddress: officeAddress.trim(),
      city: city.trim(),
      yearsOfExperience: Number(yearsOfExperience) || 0,
      specialization: specialization?.trim() || null,
      intendedPlanId: "AGENT_PRO",
      intendedBillingInterval: "MONTHLY",
    };

    const res = await submitAgentKycAction(payload);
    setIsSubmitting(false);

    if (res.success) {
      setSubmittedSuccessfully(true);
      if (onSuccess) onSuccess();
    } else {
      setErrorMessage(res.error || "Failed to submit KYC. Please check your information.");
    }
  };

  // Submit KYC and immediately launch Paystack checkout
  const handleSubmitAndPay = async () => {
    if (!agreedToTerms) {
      setErrorMessage("Please confirm and accept the compliance terms to proceed");
      return;
    }

    setIsCheckingOut(true);
    setErrorMessage(null);

    try {
      const payload: AgentKycSubmissionInput = {
        fullName: fullName.trim(),
        phoneNumber: phoneNumber.trim(),
        ninNumber: ninNumber.replace(/\D/g, ""),
        idType,
        idDocumentUrl,
        professionalBody,
        registrationNumber: registrationNumber.trim(),
        membershipDocumentUrl: membershipDocumentUrl || null,
        proofOfAddressUrl: proofOfAddressUrl || null,
        passportPhotoUrl: passportPhotoUrl || null,
        officeAddress: officeAddress.trim(),
        city: city.trim(),
        yearsOfExperience: Number(yearsOfExperience) || 0,
        specialization: specialization?.trim() || null,
        intendedPlanId: "AGENT_PRO",
        intendedBillingInterval: "MONTHLY",
      };

      await submitAgentKycAction(payload);

      const payRes = await initializeSubscriptionAction("AGENT_PRO", "MONTHLY");
      if (payRes.success && payRes.authorizationUrl) {
        window.location.href = payRes.authorizationUrl;
      } else {
        setSubmittedSuccessfully(true);
        if (onSuccess) onSuccess();
      }
    } catch (err: any) {
      setErrorMessage(err.message || "Failed to start payment checkout");
    } finally {
      setIsCheckingOut(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl p-0 overflow-hidden border-border bg-card rounded-3xl shadow-2xl">
        {/* Modal Top Header */}
        <div className="p-6 sm:p-7 bg-muted/30 border-b border-border/60">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div className="space-y-1">
              <div className="flex items-center gap-2 flex-wrap">
                <DialogTitle className="text-xl sm:text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
                  <ShieldCheck className="w-6 h-6 text-emerald-600 shrink-0" />
                  <span>Agent KYC Accreditation</span>
                </DialogTitle>
                <Badge className="bg-emerald-600 text-white text-[11px] font-bold px-2.5 py-0.5 rounded-full">
                  Zero Upfront Charge · Verify First
                </Badge>
              </div>
              <DialogDescription className="text-xs text-muted-foreground">
                Submit your professional credentials for compliance verification. You will only be billed after your accreditation is approved.
              </DialogDescription>
            </div>
          </div>

          {/* Stepper Navigation */}
          {!submittedSuccessfully && (
            <div className="grid grid-cols-4 gap-2 sm:gap-3 mt-6">
              {STEPS.map((s) => {
                const isActive = step === s.id;
                const isDone = step > s.id;
                return (
                  <div key={s.id} className="space-y-1.5">
                    <div
                      className={cn(
                        "h-1.5 rounded-full transition-all duration-300",
                        isActive || isDone ? "bg-emerald-600" : "bg-muted"
                      )}
                    />
                    <p
                      className={cn(
                        "text-[11px] font-semibold truncate",
                        isActive
                          ? "text-emerald-600 dark:text-emerald-400 font-bold"
                          : isDone
                          ? "text-foreground"
                          : "text-muted-foreground"
                      )}
                    >
                      {s.id}. {s.label}
                    </p>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Modal Body */}
        <div className="p-6 sm:p-7 max-h-[68vh] overflow-y-auto space-y-6">
          {errorMessage && (
            <div className="p-4 rounded-2xl bg-destructive/10 border border-destructive/20 text-destructive text-xs flex items-center gap-3 animate-in fade-in">
              <AlertCircle className="w-4 h-4 shrink-0" />
              <span className="font-semibold">{errorMessage}</span>
            </div>
          )}

          {submittedSuccessfully ? (
            <div className="text-center py-6 space-y-6">
              <div className="w-16 h-16 rounded-3xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center text-emerald-600 dark:text-emerald-400 mx-auto shadow-sm">
                <CheckCircle2 className="w-9 h-9" />
              </div>
              <div className="space-y-2 max-w-md mx-auto">
                <h3 className="text-xl font-bold text-foreground">
                  KYC Submitted for Compliance Review
                </h3>
                <p className="text-xs text-muted-foreground leading-relaxed">
                  Your regulatory accreditation and NIN records have been submitted. Our compliance team verifies details within 2–4 hours.
                </p>
              </div>

              <div className="p-5 rounded-2xl bg-muted/40 border border-border text-left max-w-md mx-auto space-y-3 text-xs">
                <div className="flex justify-between items-center pb-2 border-b border-border/40">
                  <span className="text-muted-foreground">Applicant Name:</span>
                  <span className="font-bold text-foreground">{fullName}</span>
                </div>
                <div className="flex justify-between items-center pb-2 border-b border-border/40">
                  <span className="text-muted-foreground">Accreditation:</span>
                  <span className="font-bold text-foreground">{professionalBody} ({registrationNumber})</span>
                </div>
                <div className="flex justify-between items-center pb-2 border-b border-border/40">
                  <span className="text-muted-foreground">Selected Plan:</span>
                  <span className="font-bold text-emerald-600">Verified Agent Pro (₦15,000/mo)</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-muted-foreground">Audit Status:</span>
                  <Badge className="bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20 text-[10px]">
                    Pending Verification (2–4 hrs)
                  </Badge>
                </div>
              </div>

              <div className="pt-2">
                <Button
                  onClick={() => onOpenChange(false)}
                  className="bg-emerald-600 text-white hover:bg-emerald-700 px-8 rounded-xl text-xs font-bold h-11 shadow-sm"
                >
                  Close &amp; Return to Dashboard
                </Button>
              </div>
            </div>
          ) : (
            <div className="space-y-6">
              {/* STEP 1: Personal Identity & NIN */}
              {step === 1 && (
                <div className="space-y-5 animate-in fade-in">
                  {/* Paid Tier Disclosure Callout */}
                  <div className="p-4 rounded-2xl bg-emerald-500/10 border border-emerald-500/20 flex items-start gap-3 text-xs text-emerald-900 dark:text-emerald-200">
                    <Sparkles className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <div className="space-y-1">
                      <strong className="font-bold block text-foreground">
                        Verified Realtor Plan Upgrade (₦15,000 / month)
                      </strong>
                      <p className="text-muted-foreground leading-relaxed">
                        To earn the official <strong>🛡️ KYC Verified badge</strong> and publish up to 25 properties, submit your Nigerian NIN and complete upgrade checkout.
                      </p>
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Full Legal Name (as on NIN) *
                      </Label>
                      <Input
                        value={fullName}
                        onChange={(e) => setFullName(e.target.value)}
                        placeholder="e.g. Babajide Adekunle Balogun"
                        className="text-xs rounded-xl h-12 bg-card"
                        required
                      />
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Active Phone / WhatsApp *
                      </Label>
                      <Input
                        value={phoneNumber}
                        onChange={(e) => setPhoneNumber(e.target.value)}
                        onBlur={(e) => setPhoneNumber(formatNigerianPhone(e.target.value))}
                        placeholder="Phone number"
                        className="text-xs font-mono rounded-xl h-12 bg-card"
                        required
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <div className="flex items-center justify-between">
                        <Label className="text-xs font-bold text-foreground">
                          National Identity Number (NIN) *
                        </Label>
                        <span className="text-[10px] font-mono text-muted-foreground">
                          {ninNumber.replace(/\D/g, "").length}/11 digits
                        </span>
                      </div>
                      <Input
                        value={ninNumber}
                        onChange={(e) => setNinNumber(e.target.value.replace(/\D/g, ""))}
                        placeholder="11-digit National ID"
                        maxLength={11}
                        className="text-xs font-mono rounded-xl h-12 tracking-widest bg-card"
                        required
                      />
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Government ID Type *
                      </Label>
                      <select
                        value={idType}
                        onChange={(e: any) => setIdType(e.target.value)}
                        className="w-full h-12 rounded-xl border border-input bg-card px-3 text-xs text-foreground shadow-xs focus:ring-2 focus:ring-emerald-500"
                      >
                        <option value="NIN_SLIP">NIN Digital Slip / Card</option>
                        <option value="DRIVERS_LICENSE">FRSC Driver&apos;s License</option>
                        <option value="INTL_PASSPORT">Nigerian International Passport</option>
                        <option value="VOTERS_CARD">INEC Voter&apos;s Card (PVC)</option>
                      </select>
                    </div>
                  </div>

                  {/* Upload Government Photo ID */}
                  <div className="space-y-1.5">
                    <Label className="text-xs font-bold text-foreground">
                      Upload Government Photo ID Document *
                    </Label>
                    <div className="p-4 rounded-2xl border border-border bg-muted/20 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-600 flex items-center justify-center shrink-0">
                          <FileCheck2 className="w-5 h-5" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-bold truncate text-foreground">
                            {idDocumentUrl ? "Government_ID_Attached.pdf" : "No document selected"}
                          </p>
                          <p className="text-[11px] text-muted-foreground">PDF, PNG, or JPG (Max 15MB)</p>
                        </div>
                      </div>

                      <label className="cursor-pointer shrink-0">
                        <input
                          type="file"
                          accept="image/*,application/pdf"
                          onChange={(e) => handleFileUpload(e, setIdDocumentUrl, "id_doc")}
                          className="hidden"
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          disabled={uploadingField === "id_doc"}
                          className="text-xs h-10 rounded-xl gap-1.5 pointer-events-none font-semibold w-full sm:w-auto"
                        >
                          {uploadingField === "id_doc" ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Upload className="w-3.5 h-3.5" />
                          )}
                          <span>{idDocumentUrl ? "Change Document" : "Attach Document"}</span>
                        </Button>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 2: Professional Accreditation */}
              {step === 2 && (
                <div className="space-y-5 animate-in fade-in">
                  <div className="p-4 rounded-2xl bg-muted/30 border border-border flex items-start gap-3 text-xs text-muted-foreground">
                    <Award className="w-5 h-5 text-emerald-600 shrink-0 mt-0.5" />
                    <span className="leading-relaxed">
                      Select your professional real estate body (LASRERA, ERCAAN, NIESV, REDAN) or Corporate Affairs Commission (CAC) Business Name registration.
                    </span>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Accreditation Authority / Body *
                      </Label>
                      <select
                        value={professionalBody}
                        onChange={(e: any) => setProfessionalBody(e.target.value)}
                        className="w-full h-12 rounded-xl border border-input bg-card px-3 text-xs text-foreground shadow-xs focus:ring-2 focus:ring-emerald-500"
                      >
                        <option value="LASRERA">LASRERA (Lagos Real Estate Regulatory Authority)</option>
                        <option value="ERCAAN">ERCAAN (Estate Rent &amp; Commission Agents)</option>
                        <option value="NIESV">NIESV / ESVARBON (Estate Surveyors &amp; Valuers)</option>
                        <option value="REDAN">REDAN (Real Estate Developers Association)</option>
                        <option value="CAC_BN">CAC Business Name (Registered Sole Broker)</option>
                        <option value="OTHER">Other Recognized Professional Body</option>
                      </select>
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Registration / License Number *
                      </Label>
                      <Input
                        value={registrationNumber}
                        onChange={(e) => setRegistrationNumber(e.target.value)}
                        placeholder="e.g. LASRERA/AGT/2024/0912"
                        className="text-xs font-mono rounded-xl h-12 bg-card"
                        required
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Years of Industry Experience
                      </Label>
                      <Input
                        type="number"
                        value={yearsOfExperience}
                        onChange={(e) => setYearsOfExperience(Number(e.target.value))}
                        min={0}
                        max={50}
                        className="text-xs rounded-xl h-12 bg-card"
                      />
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Property Specialization
                      </Label>
                      <Input
                        value={specialization}
                        onChange={(e) => setSpecialization(e.target.value)}
                        placeholder="e.g. Luxury Duplexes, Lekki Land Parcels"
                        className="text-xs rounded-xl h-12 bg-card"
                      />
                    </div>
                  </div>

                  {/* Upload Accreditation Certificate */}
                  <div className="space-y-1.5">
                    <Label className="text-xs font-bold text-foreground">
                      Upload License / Membership Certificate
                    </Label>
                    <div className="p-4 rounded-2xl border border-border bg-muted/20 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-600 flex items-center justify-center shrink-0">
                          <Award className="w-5 h-5" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-bold truncate text-foreground">
                            {membershipDocumentUrl ? "Accreditation_Certificate.pdf" : "No certificate attached"}
                          </p>
                          <p className="text-[11px] text-muted-foreground">License Certificate or Accreditation Letter</p>
                        </div>
                      </div>

                      <label className="cursor-pointer shrink-0">
                        <input
                          type="file"
                          accept="image/*,application/pdf"
                          onChange={(e) => handleFileUpload(e, setMembershipDocumentUrl, "membership_doc")}
                          className="hidden"
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          disabled={uploadingField === "membership_doc"}
                          className="text-xs h-10 rounded-xl gap-1.5 pointer-events-none font-semibold w-full sm:w-auto"
                        >
                          {uploadingField === "membership_doc" ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Upload className="w-3.5 h-3.5" />
                          )}
                          <span>{membershipDocumentUrl ? "Change Cert" : "Attach Cert"}</span>
                        </Button>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 3: Office Address & Photo */}
              {step === 3 && (
                <div className="space-y-5 animate-in fade-in">
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Operating City / State *
                      </Label>
                      <Input
                        value={city}
                        onChange={(e) => setCity(e.target.value)}
                        placeholder="e.g. Lekki, Lagos or Maitama, Abuja"
                        className="text-xs rounded-xl h-12 bg-card"
                        required
                      />
                    </div>

                    <div className="space-y-1.5">
                      <Label className="text-xs font-bold text-foreground">
                        Physical Office Address *
                      </Label>
                      <Input
                        value={officeAddress}
                        onChange={(e) => setOfficeAddress(e.target.value)}
                        placeholder="e.g. Suite 12, Admiralty Way, Lekki Phase 1"
                        className="text-xs rounded-xl h-12 bg-card"
                        required
                      />
                    </div>
                  </div>

                  {/* Proof of Address */}
                  <div className="space-y-1.5">
                    <Label className="text-xs font-bold text-foreground">
                      Proof of Office Address (Utility Bill / Tenancy)
                    </Label>
                    <div className="p-4 rounded-2xl border border-border bg-muted/20 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-600 flex items-center justify-center shrink-0">
                          <MdCorporateFare className="w-5 h-5" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-bold truncate text-foreground">
                            {proofOfAddressUrl ? "Office_Proof_Of_Address.pdf" : "Upload Utility Bill"}
                          </p>
                          <p className="text-[11px] text-muted-foreground">PHCN bill, LAWMA receipt, or Tenancy Agreement</p>
                        </div>
                      </div>

                      <label className="cursor-pointer shrink-0">
                        <input
                          type="file"
                          accept="image/*,application/pdf"
                          onChange={(e) => handleFileUpload(e, setProofOfAddressUrl, "proof_address")}
                          className="hidden"
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          disabled={uploadingField === "proof_address"}
                          className="text-xs h-10 rounded-xl gap-1.5 pointer-events-none font-semibold w-full sm:w-auto"
                        >
                          {uploadingField === "proof_address" ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Upload className="w-3.5 h-3.5" />
                          )}
                          <span>{proofOfAddressUrl ? "Change Bill" : "Attach Bill"}</span>
                        </Button>
                      </label>
                    </div>
                  </div>

                  {/* Portrait Headshot */}
                  <div className="space-y-1.5">
                    <Label className="text-xs font-bold text-foreground">
                      Passport Portrait Photograph
                    </Label>
                    <div className="p-4 rounded-2xl border border-border bg-muted/20 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <div className="w-10 h-10 rounded-xl bg-emerald-500/10 text-emerald-600 flex items-center justify-center shrink-0">
                          <User className="w-5 h-5" />
                        </div>
                        <div className="min-w-0">
                          <p className="text-xs font-bold truncate text-foreground">
                            {passportPhotoUrl ? "Agent_Portrait_Headshot.jpg" : "Clear portrait photograph"}
                          </p>
                          <p className="text-[11px] text-muted-foreground">Displayed on your public Verified Agent badge card</p>
                        </div>
                      </div>

                      <label className="cursor-pointer shrink-0">
                        <input
                          type="file"
                          accept="image/*"
                          onChange={(e) => handleFileUpload(e, setPassportPhotoUrl, "passport_photo")}
                          className="hidden"
                        />
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          disabled={uploadingField === "passport_photo"}
                          className="text-xs h-10 rounded-xl gap-1.5 pointer-events-none font-semibold w-full sm:w-auto"
                        >
                          {uploadingField === "passport_photo" ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                          ) : (
                            <Upload className="w-3.5 h-3.5" />
                          )}
                          <span>{passportPhotoUrl ? "Change Photo" : "Attach Photo"}</span>
                        </Button>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 4: Pay & Upgrade */}
              {step === 4 && (
                <div className="space-y-5 animate-in fade-in">
                  {/* Paid Tier Highlight Banner */}
                  <div className="p-6 rounded-3xl border border-emerald-500/40 bg-gradient-to-br from-emerald-950/25 via-card to-background space-y-4">
                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-border/60">
                      <div>
                        <span className="text-[11px] font-extrabold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">
                          Selected Subscription Tier
                        </span>
                        <h4 className="text-xl font-extrabold text-foreground flex items-center gap-2 mt-0.5">
                          <ShieldCheck className="w-5 h-5 text-emerald-600" />
                          Verified Agent Pro
                        </h4>
                      </div>
                      <div className="text-left sm:text-right">
                        <span className="text-3xl font-extrabold text-emerald-600 dark:text-emerald-400">
                          ₦15,000
                        </span>
                        <span className="text-xs text-muted-foreground font-medium"> / month</span>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5 text-xs">
                      {[
                        "🛡️ Official KYC Verified Agent Badge",
                        "Up to 25 Active Property Listings",
                        "3 Featured Homepage Promotional Slots",
                        "Direct WhatsApp CRM & Lead Routing",
                        "Priority 2–4 Hour Listing Moderation",
                        "LASRERA & NIN Verified Trust Profile",
                      ].map((feat, idx) => (
                        <div key={idx} className="flex items-center gap-2 text-foreground font-medium">
                          <Check className="w-4 h-4 text-emerald-600 shrink-0" />
                          <span>{feat}</span>
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* Summary Details Grid */}
                  <div className="p-5 rounded-2xl bg-muted/40 border border-border space-y-3 text-xs">
                    <h5 className="font-bold text-foreground text-xs uppercase tracking-wider text-muted-foreground">
                      Submitted KYC Application Summary
                    </h5>
                    <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-muted-foreground pt-1">
                      <div>
                        <span className="block text-[11px]">Full Name:</span>
                        <strong className="text-foreground">{fullName}</strong>
                      </div>
                      <div>
                        <span className="block text-[11px]">NIN Number:</span>
                        <strong className="text-foreground font-mono">•••••••{ninNumber.slice(-4)}</strong>
                      </div>
                      <div>
                        <span className="block text-[11px]">Accreditation:</span>
                        <strong className="text-foreground">{professionalBody}</strong>
                      </div>
                      <div>
                        <span className="block text-[11px]">License Number:</span>
                        <strong className="text-foreground font-mono">{registrationNumber}</strong>
                      </div>
                      <div>
                        <span className="block text-[11px]">Operating Location:</span>
                        <strong className="text-foreground">{city}</strong>
                      </div>
                      <div>
                        <span className="block text-[11px]">Experience:</span>
                        <strong className="text-foreground">{yearsOfExperience} Years</strong>
                      </div>
                    </div>
                  </div>

                  {/* Compliance Checkbox */}
                  <div className="p-4 rounded-2xl border border-border bg-card">
                    <label className="flex items-start gap-3 cursor-pointer">
                      <input
                        type="checkbox"
                        checked={agreedToTerms}
                        onChange={(e) => setAgreedToTerms(e.target.checked)}
                        className="mt-0.5 rounded border-border text-emerald-600 focus:ring-emerald-500"
                      />
                      <span className="text-xs text-muted-foreground leading-relaxed">
                        I hereby attest that all NIN, regulatory accreditation, and business details provided are authentic, true, and valid under Nigerian law.
                      </span>
                    </label>
                  </div>
                </div>
              )}

              {/* Step Navigation Buttons */}
              <div className="flex items-center justify-between pt-4 border-t border-border/60 gap-3">
                {step > 1 ? (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleBack}
                    className="gap-1.5 text-xs rounded-xl font-semibold h-11 px-5"
                  >
                    <ArrowLeft className="w-4 h-4" /> Back
                  </Button>
                ) : (
                  <Button
                    type="button"
                    variant="ghost"
                    onClick={() => onOpenChange(false)}
                    className="text-xs text-muted-foreground h-11 px-5"
                  >
                    Cancel
                  </Button>
                )}

                {step < 4 ? (
                  <Button
                    type="button"
                    onClick={handleNext}
                    className="bg-emerald-600 text-white hover:bg-emerald-700 gap-2 text-xs rounded-xl font-bold h-11 px-6 shadow-md"
                  >
                    <span>Continue</span>
                    <ArrowRight className="w-4 h-4" />
                  </Button>
                ) : (
                  <Button
                    type="button"
                    disabled={isSubmitting || !agreedToTerms}
                    onClick={handleSubmitApplication}
                    className="bg-emerald-600 text-white hover:bg-emerald-700 gap-2 text-xs rounded-xl font-bold h-11 px-6 shadow-lg shadow-emerald-600/20 cursor-pointer"
                  >
                    {isSubmitting ? (
                      <>
                        <Loader2 className="w-4 h-4 animate-spin" />
                        <span>Submitting for Review...</span>
                      </>
                    ) : (
                      <>
                        <ShieldCheck className="w-4 h-4" />
                        <span>Submit for Compliance Review (Free)</span>
                      </>
                    )}
                  </Button>
                )}
              </div>
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
