import { useState, useMemo } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import "react-phone-number-input/style.css";
import PhoneInput from "react-phone-number-input";
import { ArrowLeft, X, Home, Building, Layers, UserX, User, Users, UsersRound, Building2, Zap, Calendar, Search, CircleSlash, Coins, Wallet, Banknote, TrendingUp } from "lucide-react";
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
import { useNavigate } from "react-router-dom";

type Step = 
  | "Q1_TRADE" 
  | "Q2_CREWS" 
  | "Q3_TIMELINE" 
  | "Q4_SPEND" 
  | "Q5_NAME" 
  | "Q6_PHONE";

type StandardTrackingFieldKey = string;
type RegisteredCustomFieldId = string;
type TrackingCustomField = { value?: unknown; label: string };
type TrackingFileField = { file?: File; label: string };
type TrackingImageDataField = { dataUrl?: string; label: string };

const postTrackingEvent = (
  trackingPayload: Record<string, unknown> & {
    formData: Record<StandardTrackingFieldKey, unknown>;
    formLabels: Record<StandardTrackingFieldKey, string>;
  },
  options: {
    customFields?: Record<RegisteredCustomFieldId, TrackingCustomField>;
    fileFields?: Record<RegisteredCustomFieldId, TrackingFileField>;
    imageDataFields?: Record<RegisteredCustomFieldId, TrackingImageDataField>;
  } = {},
) => {
  const { customFields = {}, fileFields = {}, imageDataFields = {} } = options;
  const eventPayload = {
    ...trackingPayload,
    formData: { ...trackingPayload.formData },
    formLabels: { ...trackingPayload.formLabels },
  };
  const body = new FormData();

  for (const [key, field] of Object.entries(customFields)) {
    if (field.value === undefined) continue;
    eventPayload.formData[key] = field.value;
    eventPayload.formLabels[key] = field.label;
  }

  for (const [key, field] of Object.entries(imageDataFields)) {
    const dataUrl = field.dataUrl;
    if (!dataUrl) continue;
    if (!dataUrl.startsWith("data:image/")) {
      throw new Error("Image data field must be a data:image/* base64 string");
    }
    eventPayload.formData[key] = dataUrl;
    eventPayload.formLabels[key] = field.label;
  }

  for (const [key, field] of Object.entries(fileFields)) {
    const file = field.file;
    if (!file) continue;
    if (file.size > 50 * 1024 * 1024) {
      throw new Error("File must be 50 MB or smaller");
    }
    eventPayload.formData[key] = {
      filename: file.name,
      size: file.size,
      type: file.type || "application/octet-stream",
    };
    eventPayload.formLabels[key] = field.label;
    body.append(key, file, file.name);
  }

  for (const key of Object.keys(eventPayload.formData)) {
    eventPayload.formLabels[key] ||= key;
  }

  body.append("event", JSON.stringify(eventPayload));

  fetch("https://backend.leadconnectorhq.com/external-tracking/events", {
    method: "POST",
    headers: {
      version: "2021-07-28",
    },
    body,
  }).catch(() => {}); // Fire-and-forget
};

interface QuizModalProps {
  isOpen: boolean;
  onClose: () => void;
}

const PROGRESS_MAP = [50, 62, 74, 84, 91, 96, 100];

export function QuizModal({ isOpen, onClose }: QuizModalProps) {
  const [history, setHistory] = useState<Step[]>(["Q1_TRADE"]);
  const [displayStep, setDisplayStep] = useState<Step>("Q1_TRADE");
  const [animClass, setAnimClass] = useState("animate-in fade-in slide-in-from-bottom-4 duration-500");
  const [formData, setFormData] = useState<Record<string, string>>({});
  const navigate = useNavigate();
  
  const currentStep = displayStep;
  const progress = PROGRESS_MAP[Math.min(history.length - 1, PROGRESS_MAP.length - 1)];

  const handleNext = (nextStep: Step, key?: string, value?: string) => {
    if (key && value !== undefined) {
      setFormData(prev => ({ ...prev, [key]: value }));
    }
    setAnimClass("animate-slide-out-left");
    setTimeout(() => {
      setHistory(prev => [...prev, nextStep]);
      setDisplayStep(nextStep);
      setAnimClass("animate-slide-in-right");
    }, 250);
  };

  const handleBack = () => {
    if (history.length > 1) {
      setAnimClass("animate-slide-out-right");
      setTimeout(() => {
        const newHistory = history.slice(0, -1);
        setHistory(newHistory);
        setDisplayStep(newHistory[newHistory.length - 1]);
        setAnimClass("animate-slide-in-left");
      }, 250);
    }
  };

  const handleClose = () => {
    // Only allow close on first step
    if (history.length === 1) {
      onClose();
      // Reset after animation
      setTimeout(() => {
        setHistory(["Q1_TRADE"]);
        setDisplayStep("Q1_TRADE");
        setAnimClass("animate-in fade-in slide-in-from-bottom-4 duration-500");
        setFormData({});
      }, 300);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const trackingPayload = {
      type: "external_form_submission",
      timestamp: Date.now(),
      formId: "Contractor Lead Generation Quiz",
      formData: {
        first_name: formData.name?.split(" ")[0] || "",
        last_name: formData.name?.split(" ").slice(1).join(" ") || "",
        phone: formData.phone || "",
        source: "sitesfunnelusa",
      },
      formLabels: {
        first_name: "First Name",
        last_name: "Last Name",
        phone: "Phone",
        source: "Contact Source",
      },
      url: window.location.href,
      title: document.title,
      path: window.location.pathname,
      userAgent: navigator.userAgent,
      trackingId: "tk_5a61238b89b9410b917d0cd112d42265",
      locationId: "kVaOFIx6l0Mqf5mx1hur",
      sessionId: crypto.randomUUID(),
      properties: {
        deviceType: /Mobile|Android|iPhone/i.test(navigator.userAgent)
          ? "mobile"
          : "desktop",
      },
      tags: ["US Website Funnel Lead"],
    };

    postTrackingEvent(trackingPayload, {
      customFields: {
        "S8ZpkDcsccPmJ5PAbPil": { value: formData.trade, label: "What kind of contracting work do you do?" },
        "1qWeFx6dx2SIiv8IANdY": { value: formData.crews, label: "How many crews do you have?" },
        "mqJ0WWKbLRmb0ir1Yr1j": { value: formData.timeline, label: "How soon do you want more leads coming in?" },
        "rNTyugo1b2uyZyWhnWTm": { value: formData.spend, label: "How much do you spend on marketing per month?" },
        "l4QR6EfNa0OKacYsXpyG": { value: "dryftsites funnel 01", label: "lead type" },
      }
    });

    console.log("Submitting lead:", formData);
    onClose();
    navigate("/we-will-call-you");
    setTimeout(() => {
      setHistory(["Q1_TRADE"]);
      setDisplayStep("Q1_TRADE");
      setAnimClass("animate-in fade-in slide-in-from-bottom-4 duration-500");
      setFormData({});
    }, 300);
  };

  // Prevent closing by clicking outside if not on first step
  const handleInteractOutside = (e: Event) => {
    if (history.length > 1) {
      e.preventDefault();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
      <DialogContent 
        className="max-w-2xl w-full h-[100dvh] sm:h-auto sm:max-h-[90vh] p-0 sm:rounded-2xl border-0 sm:border flex flex-col gap-0 bg-white overflow-hidden [&>button[aria-label=Close]]:hidden"
        onInteractOutside={handleInteractOutside}
        onEscapeKeyDown={handleInteractOutside}
      >
        <VisuallyHidden>
          <DialogTitle>Contractor Lead Generation Quiz</DialogTitle>
        </VisuallyHidden>

        {/* Header Area */}
        <div className="flex-shrink-0 bg-white z-10 pt-4 sm:pt-6 px-4 sm:px-8 pb-4">
          <div className="flex items-center justify-between mb-4 h-8">
            {history.length > 1 ? (
              <button 
                onClick={handleBack}
                className="flex items-center text-sm font-medium text-gray-500 hover:text-gray-900 transition-colors"
              >
                <ArrowLeft className="w-4 h-4 mr-1" />
                Back
              </button>
            ) : (
              <div /> // Spacer
            )}
            
            {history.length === 1 && (
              <button 
                onClick={handleClose}
                className="text-gray-400 hover:text-gray-600 transition-colors p-1"
              >
                <X className="w-6 h-6" />
              </button>
            )}
          </div>

          {history.length === 1 && (
            <h2 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center px-4">
              We Help Contractors Get More Leads — For Just <span className="text-[#FF5C00]">$247/month</span>
            </h2>
          )}

          {/* Progress Bar */}
          <div className="w-full h-8 bg-gray-100 rounded-full overflow-hidden relative shadow-inner">
            <div 
              className="absolute top-0 left-0 h-full bg-[#22c55e] transition-all duration-300 ease-out flex items-center justify-end pr-3"
              style={{ width: `${progress}%` }}
            >
              <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent -translate-x-full animate-[shimmer_2s_infinite]"></div>
              {/* Frosted glass effect on the fill */}
              <div className="absolute inset-0 bg-white/20 backdrop-blur-[2px]"></div>
              <span className="relative z-10 text-sm font-bold text-white drop-shadow-md">
                {progress}%
              </span>
            </div>
          </div>
        </div>

        {/* Content Area */}
        <div className="flex-1 overflow-y-auto px-4 sm:px-8 pb-8 pt-4 flex flex-col">
          <div className="max-w-md w-full mx-auto flex-1 flex flex-col">
            
            {currentStep === "Q1_TRADE" && (
              <div className={animClass}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">What kind of contracting work do you do?</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { label: 'Residential', value: 'Residential', icon: Home },
                    { label: 'Commercial', value: 'Commercial', icon: Building },
                    { label: 'Both', value: 'Both', icon: Layers },
                    { label: 'I Am Not a Contractor', value: 'I Am Not a Contractor', icon: UserX }
                  ].map(option => (
                    <button
                      key={option.value}
                      onClick={() => handleNext("Q2_CREWS", "trade", option.value)}
                      className="group flex flex-col items-center justify-center gap-3 p-4 rounded-xl border-2 border-gray-100 bg-white text-center hover:border-[#FF5C00] hover:bg-[#FF5C00]/5 transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation"
                    >
                      <option.icon className="w-8 h-8 text-[#383838] group-hover:text-[#FF5C00] transition-colors" />
                      <span className="text-lg font-medium text-[#383838] group-hover:text-[#FF5C00] transition-colors">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {currentStep === "Q2_CREWS" && (
              <div className={animClass}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">How many crews do you have?</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { label: 'Just me', icon: User },
                    { label: '2-3 crews', icon: Users },
                    { label: '4-6 crews', icon: UsersRound },
                    { label: '6+ crews', icon: Building2 }
                  ].map(option => (
                    <button
                      key={option.label}
                      onClick={() => handleNext("Q3_TIMELINE", "crews", option.label)}
                      className="group flex flex-col items-center justify-center gap-3 p-4 rounded-xl border-2 border-gray-100 bg-white text-center hover:border-[#FF5C00] hover:bg-[#FF5C00]/5 transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation"
                    >
                      <option.icon className="w-8 h-8 text-[#383838] group-hover:text-[#FF5C00] transition-colors" />
                      <span className="text-lg font-medium text-[#383838] group-hover:text-[#FF5C00] transition-colors">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {currentStep === "Q3_TIMELINE" && (
              <div className={animClass}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">How soon do you want more leads coming in?</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { label: 'ASAP / Right now', icon: Zap },
                    { label: 'Next 1-3 months', icon: Calendar },
                    { label: 'Just researching', icon: Search, className: "col-span-2" }
                  ].map(option => (
                    <button
                      key={option.label}
                      onClick={() => handleNext("Q4_SPEND", "timeline", option.label)}
                      className={`group flex flex-col items-center justify-center gap-3 p-4 rounded-xl border-2 border-gray-100 bg-white text-center hover:border-[#FF5C00] hover:bg-[#FF5C00]/5 transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation ${option.className || ""}`}
                    >
                      <option.icon className="w-8 h-8 text-[#383838] group-hover:text-[#FF5C00] transition-colors" />
                      <span className="text-lg font-medium text-[#383838] group-hover:text-[#FF5C00] transition-colors">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {currentStep === "Q4_SPEND" && (
              <div className={animClass}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">How much do you spend on marketing per month?</h3>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { label: 'Nothing', icon: CircleSlash },
                    { label: 'Up to $1k', icon: Coins },
                    { label: '$1k-3k', icon: Wallet },
                    { label: '$3k-6k', icon: Banknote },
                    { label: '$6k+', icon: TrendingUp, className: "col-span-2" }
                  ].map(option => (
                    <button
                      key={option.label}
                      onClick={() => handleNext("Q5_NAME", "spend", option.label)}
                      className={`group flex flex-col items-center justify-center gap-3 p-4 rounded-xl border-2 border-gray-100 bg-white text-center hover:border-[#FF5C00] hover:bg-[#FF5C00]/5 transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation ${option.className || ""}`}
                    >
                      <option.icon className="w-8 h-8 text-[#383838] group-hover:text-[#FF5C00] transition-colors" />
                      <span className="text-lg font-medium text-[#383838] group-hover:text-[#FF5C00] transition-colors">{option.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            )}

            {currentStep === "Q5_NAME" && (
              <div className={`${animClass} flex flex-col h-full`}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">First and last name</h3>
                <div className="flex-1">
                  <input 
                    autoFocus
                    placeholder="Your name"
                    className="flex h-14 w-full rounded-xl border border-gray-200 bg-white px-3 py-2 text-lg ring-offset-white file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-gray-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#FF5C00] disabled:cursor-not-allowed disabled:opacity-50"
                    value={formData.name || ""}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' && formData.name) {
                        handleNext("Q6_PHONE");
                      }
                    }}
                  />
                </div>
                <Button 
                  onClick={() => handleNext("Q6_PHONE")}
                  disabled={!formData.name}
                  className="w-full h-14 text-lg font-bold rounded-xl mt-6 bg-[#1a1a1a] hover:bg-[#383838] text-white transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation"
                >
                  Continue
                </Button>
              </div>
            )}

            {currentStep === "Q6_PHONE" && (
              <form onSubmit={handleSubmit} className={`${animClass} flex flex-col h-full`}>
                <h3 className="text-2xl font-bold text-[#1a1a1a] mb-6 text-center">Your mobile phone</h3>
                <div className="flex-1">
                  <div className="relative">
                    <PhoneInput
                      defaultCountry="US"
                      placeholder="(555) 123-4567"
                      value={formData.phone || ""}
                      onChange={(value) => setFormData(prev => ({ ...prev, phone: value || "" }))}
                      className="flex h-14 w-full rounded-xl border border-gray-200 bg-white px-4 py-1 text-lg shadow-sm transition-colors focus-within:ring-1 focus-within:ring-[#FF5C00] [&_.PhoneInputInput]:border-none [&_.PhoneInputInput]:outline-none [&_.PhoneInputInput]:bg-transparent [&_.PhoneInputInput]:w-full [&_.PhoneInputInput]:ml-3 [&_.PhoneInputCountryIcon]:w-7 [&_.PhoneInputCountryIcon]:h-5 [&_.PhoneInputCountryIcon]:shadow-sm [&_.PhoneInputCountrySelectArrow]:ml-2 [&_.PhoneInputCountrySelectArrow]:w-3 [&_.PhoneInputCountrySelectArrow]:h-3 [&_.PhoneInputCountrySelectArrow]:opacity-50"
                    />
                  </div>
                  <p className="text-sm text-gray-500 mt-3 text-center">
                    We'll only use this to call you back — no spam!
                  </p>
                </div>
                <Button 
                  type="submit"
                  disabled={!formData.phone}
                  className="w-full h-14 text-lg font-bold rounded-xl mt-6 bg-[#FF5C00] hover:bg-[#E05200] text-white shadow-lg hover:shadow-xl transition-all duration-150 ease-out active:scale-[0.97] active:duration-100 [-webkit-tap-highlight-color:transparent] touch-manipulation"
                >
                  Yes, I Want More Jobs
                </Button>
              </form>
            )}

          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
