import React, { useState, useEffect } 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 { CheckCircle2, ShieldCheck, MapPin, ArrowRight, Loader2, AlertCircle } from "lucide-react";
import { toast } from "sonner";
import { submitLeadToCrm } from "@/lib/leadSubmission";
import { AddressAutocompleteInput } from "@/components/AddressAutocompleteInput";

interface OfferModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialAddress?: string;
}

export default function OfferModal({ isOpen, onClose, initialAddress = "" }: OfferModalProps) {
  const [step, setStep] = useState<"form" | "success">("form");
  const [loading, setLoading] = useState(false);
  const [successAnim, setSuccessAnim] = useState(false);
  const [formData, setFormData] = useState({
    address: initialAddress,
    name: "",
    phone: "",
    email: "",
    timeline: "asap",
  });
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // Sync initial address if passed
  useEffect(() => {
    if (initialAddress) {
      setFormData((prev) => ({ ...prev, address: initialAddress }));
    }
  }, [initialAddress]);

  useEffect(() => {
    if (isOpen) return;
    const timer = window.setTimeout(() => {
      setStep("form");
      setSuccessAnim(false);
      setErrors({});
      setLoading(false);
    }, 300);
    return () => window.clearTimeout(timer);
  }, [isOpen]);

  const validateForm = () => {
    const newErrors: { [key: string]: string } = {};
    if (!formData.address.trim()) {
      newErrors.address = "Please enter your property address.";
    }
    if (!formData.name.trim()) {
      newErrors.name = "Please enter your full name.";
    }
    const phoneDigits = formData.phone.replace(/\D/g, "");
    if (phoneDigits.length < 10) {
      newErrors.phone = "Please enter a valid 10-digit phone number.";
    }
    if (formData.email && !formData.email.includes("@")) {
      newErrors.email = "Please enter a valid email address.";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) {
      toast.error("Please correct the highlighted fields before submitting.");
      return;
    }

    setLoading(true);

    try {
      const data = await submitLeadToCrm({
        propertyAddress: formData.address,
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        timeline: formData.timeline,
        leadSource: "location-offer-modal",
        consent: false,
      });

      if (data.success) {
        setStep("success");
        setTimeout(() => setSuccessAnim(true), 50);
        toast.success("Cash offer request received.");
      } else {
        toast.error("Failed to submit request. Please try again.");
      }
    } catch {
      toast.error("We could not save your request just now. Please try again shortly.");
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setStep("form");
    setSuccessAnim(false);
    setFormData({ address: "", name: "", phone: "", email: "", timeline: "asap" });
    setErrors({});
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleReset()}>
      <DialogContent className="offer-dialog sm:max-w-xl !bg-white !text-[#032b4e] border !border-[#dce7ec] p-6 sm:p-8 rounded-xl shadow-2xl">
        <DialogHeader className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="editorial-badge">Free & No Obligation</span>
            <span className="text-xs !text-[#5c7181] font-medium">Response in &lt; 24 Hours</span>
          </div>
          <DialogTitle className="font-serif text-2xl sm:text-3xl font-semibold tracking-tight !text-[#032b4e]">
            {step === "form" ? "Request Your Cash Offer" : "Offer Request Received"}
          </DialogTitle>
          <DialogDescription className="text-sm !text-[#5c7181] leading-relaxed">
            {step === "form"
              ? "Provide your property details below. No obligation, no repairs required, and complete confidentiality."
              : "We are reviewing your property details. A local home specialist will contact you shortly."}
          </DialogDescription>
        </DialogHeader>

        {step === "form" ? (
          <form onSubmit={handleSubmit} className="space-y-4 pt-2">
            <div className="space-y-1.5">
              <Label htmlFor="modal-address" className="text-xs font-semibold uppercase tracking-wider !text-[#032b4e]">
                Property Address <span className="!text-[#00a978]">*</span>
              </Label>
              <div className="relative">
                <MapPin className="absolute left-3.5 top-3.5 w-4 h-4 !text-[#5c7181]" />
                <AddressAutocompleteInput
                  id="modal-address"
                  name="address"
                  autoComplete="street-address"
                  placeholder="Start typing U.S. property address..."
                  value={formData.address}
                  onValueChange={(value) => {
                    setFormData({ ...formData, address: value });
                    if (errors.address) setErrors({ ...errors, address: "" });
                  }}
                  onMapsUnavailable={() => toast.error("Address suggestions are unavailable right now. You can still enter the address manually.")}
                  className={`pl-10 !bg-white border !text-[#032b4e] py-3 h-11 text-sm focus-visible:!ring-[#00b887] ${
                    errors.address ? "border-destructive focus-visible:ring-destructive" : "border-border"
                  }`}
                />
              </div>
              {errors.address && (
                <p className="text-xs text-destructive flex items-center gap-1">
                  <AlertCircle className="w-3.5 h-3.5" />
                  {errors.address}
                </p>
              )}
              <p className="text-xs !text-[#5c7181]">Select your address from the Google Places autocomplete dropdown.</p>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-1.5">
                <Label htmlFor="modal-name" className="text-xs font-semibold uppercase tracking-wider text-foreground">
                  Your Full Name <span className="text-primary">*</span>
                </Label>
                <Input
                  id="modal-name"
                  placeholder="John Smith"
                  value={formData.name}
                  onChange={(e) => {
                    setFormData({ ...formData, name: e.target.value });
                    if (errors.name) setErrors({ ...errors, name: "" });
                  }}
                  className={`bg-background border text-foreground py-3 h-11 text-sm focus-visible:ring-primary ${
                    errors.name ? "border-destructive focus-visible:ring-destructive" : "border-border"
                  }`}
                />
                {errors.name && (
                  <p className="text-xs text-destructive flex items-center gap-1">
                    <AlertCircle className="w-3.5 h-3.5" />
                    {errors.name}
                  </p>
                )}
              </div>

              <div className="space-y-1.5">
                <Label htmlFor="modal-phone" className="text-xs font-semibold uppercase tracking-wider text-foreground">
                  Phone Number <span className="text-primary">*</span>
                </Label>
                <Input
                  id="modal-phone"
                  placeholder="(555) 000-0000"
                  type="tel"
                  value={formData.phone}
                  onChange={(e) => {
                    setFormData({ ...formData, phone: e.target.value });
                    if (errors.phone) setErrors({ ...errors, phone: "" });
                  }}
                  className={`bg-background border text-foreground py-3 h-11 text-sm focus-visible:ring-primary ${
                    errors.phone ? "border-destructive focus-visible:ring-destructive" : "border-border"
                  }`}
                />
                {errors.phone && (
                  <p className="text-xs text-destructive flex items-center gap-1">
                    <AlertCircle className="w-3.5 h-3.5" />
                    {errors.phone}
                  </p>
                )}
              </div>
            </div>

            <div className="space-y-1.5">
              <Label htmlFor="modal-email" className="text-xs font-semibold uppercase tracking-wider !text-[#032b4e]">
                Email Address <span className="!text-[#5c7181] font-normal">(Optional)</span>
              </Label>
              <Input
                id="modal-email"
                placeholder="john@example.com"
                type="email"
                value={formData.email}
                onChange={(e) => {
                  setFormData({ ...formData, email: e.target.value });
                  if (errors.email) setErrors({ ...errors, email: "" });
                }}
                className={`bg-background border text-foreground py-3 h-11 text-sm focus-visible:ring-primary ${
                  errors.email ? "border-destructive focus-visible:ring-destructive" : "border-border"
                }`}
              />
              {errors.email && (
                <p className="text-xs text-destructive flex items-center gap-1">
                  <AlertCircle className="w-3.5 h-3.5" />
                  {errors.email}
                </p>
              )}
            </div>

            <div className="space-y-2 pt-1">
              <Label className="text-xs font-semibold uppercase tracking-wider !text-[#032b4e]">
                Desired Selling Timeline
              </Label>
              <div className="grid grid-cols-3 gap-2.5">
                {[
                  { id: "asap", label: "As Soon as Possible" },
                  { id: "30days", label: "Within 30 Days" },
                  { id: "flexible", label: "Flexible / Later" },
                ].map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    onClick={() => setFormData({ ...formData, timeline: item.id })}
                    className={`py-2.5 px-3 text-xs font-medium rounded-md border text-center transition-all cursor-pointer ${
                      formData.timeline === item.id
                        ? "!border-[#00b887] !bg-[#d7f8eb] !text-[#007d5d] font-semibold"
                        : "!border-[#dce7ec] !bg-white !text-[#032b4e] hover:!bg-[#f2f7f9]"
                    }`}
                  >
                    {item.label}
                  </button>
                ))}
              </div>
            </div>

            <div className="pt-2">
              <Button
                type="submit"
                disabled={loading}
                className="w-full !bg-[#00b887] hover:!bg-[#009e76] !text-white font-medium py-3.5 h-12 rounded-md shadow-sm transition-all active:scale-98 text-sm flex items-center justify-center gap-2"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>Preparing Your Offer...</span>
                  </>
                ) : (
                  <>
                    <span>Get My Free Cash Offer</span>
                    <ArrowRight className="w-4 h-4" />
                  </>
                )}
              </Button>
            </div>

            <div className="flex items-center gap-2 text-xs !text-[#5c7181] pt-1 justify-center">
              <ShieldCheck className="w-4 h-4 text-emerald-600 shrink-0" />
              <span>Your privacy is secure. No realtor spam or public listing required.</span>
            </div>
          </form>
        ) : (
          <div className={`space-y-6 pt-6 pb-4 text-center transition-all duration-500 transform ${successAnim ? "opacity-100 scale-100" : "opacity-0 scale-95"}`}>
            <div className="w-20 h-20 bg-emerald-100 text-emerald-700 rounded-full flex items-center justify-center mx-auto shadow-md animate-bounce">
              <CheckCircle2 className="w-10 h-10" />
            </div>
            <div className="space-y-2">
              <h3 className="font-serif text-2xl font-bold text-foreground">Cash Offer Request Submitted!</h3>
              <p className="text-sm text-muted-foreground max-w-md mx-auto leading-relaxed">
                Thank you, <span className="font-semibold text-foreground">{formData.name}</span>. Our acquisitions team is analyzing market comparables for <span className="font-semibold text-foreground">{formData.address}</span>. We will call you at <span className="font-semibold text-foreground">{formData.phone}</span> within 24 hours.
              </p>
            </div>
            <div className="p-4 bg-secondary/50 rounded-lg border border-border text-left space-y-2.5 text-xs text-muted-foreground max-w-md mx-auto">
              <div className="flex justify-between">
                <span>Request Status:</span>
                <span className="font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded">Active Review</span>
              </div>
              <div className="flex justify-between">
                <span>Response Timeframe:</span>
                <span className="font-semibold text-foreground">Within 24 Hours</span>
              </div>
              <div className="flex justify-between">
                <span>Immediate Support:</span>
                <span className="font-semibold text-foreground">(240) 410-5636</span>
              </div>
            </div>
            <div className="pt-2">
              <Button
                onClick={handleReset}
                className="w-full max-w-md bg-primary hover:bg-primary/90 text-primary-foreground font-medium py-3.5 h-12 rounded-md shadow-sm"
              >
                Done / Return to Home
              </Button>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}
