"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X, Lightning, CaretRight, CheckCircle } from "@phosphor-icons/react";
import Button from "@/components/ui/Button";

export default function FloatingQuoteWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [step, setStep] = useState(1);
  const [propertyType, setPropertyType] = useState<"residential" | "commercial">("residential");
  const [monthlyBill, setMonthlyBill] = useState(5000);
  const [pincode, setPincode] = useState("");
  const [submitted, setSubmitted] = useState(false);

  // Estimation math
  const systemKw = (monthlyBill / 1000) * 0.8;
  const estimatedCost = Math.round(systemKw * 48000);
  const subsidy = Math.min(78000, Math.round(systemKw * 18000));
  const netCost = Math.max(25000, estimatedCost - subsidy);
  const annualSavings = Math.round(monthlyBill * 10.8);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (pincode.trim().length >= 4) {
      setSubmitted(true);
    }
  };

  const reset = () => {
    setIsOpen(false);
    setStep(1);
    setSubmitted(false);
  };

  return (
    <>
      {/* Floating Trigger Button */}
      <div className="fixed bottom-6 right-6 z-40">
        <motion.button
          onClick={() => setIsOpen(true)}
          whileHover={{ scale: 1.05, y: -2 }}
          whileTap={{ scale: 0.95 }}
          className="group flex items-center gap-2.5 rounded-full border border-amber-400/40 bg-zinc-950/90 px-4 py-3 text-xs font-bold text-white shadow-[0_10px_30px_rgba(245,158,11,0.3)] backdrop-blur-xl transition-all duration-300 hover:border-amber-400 hover:bg-black"
        >
          <span className="relative flex h-3 w-3 items-center justify-center">
            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-amber-400 opacity-75" />
            <span className="relative inline-flex h-2 w-2 rounded-full bg-amber-500" />
          </span>
          <Lightning size={16} weight="fill" className="text-amber-400" />
          <span>Instant Roof Quote</span>
        </motion.button>
      </div>

      {/* Interactive Modal Drawer */}
      <AnimatePresence>
        {isOpen && (
          <div className="fixed inset-0 z-50 flex items-end justify-end p-4 sm:p-6">
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={reset}
              className="fixed inset-0 bg-black/60 backdrop-blur-sm"
            />

            {/* Modal Drawer Card */}
            <motion.div
              initial={{ opacity: 0, y: 40, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 40, scale: 0.95 }}
              transition={{ type: "spring", stiffness: 300, damping: 30 }}
              className="relative z-10 w-full max-w-md overflow-hidden rounded-3xl border border-white/20 bg-zinc-950 p-6 text-white shadow-[0_20px_50px_rgba(0,0,0,0.8)] backdrop-blur-2xl"
            >
              {/* Header */}
              <div className="mb-6 flex items-center justify-between border-b border-white/10 pb-4">
                <div className="flex items-center gap-2">
                  <div className="flex h-8 w-8 items-center justify-center rounded-xl bg-amber-500/20 text-amber-400 border border-amber-500/40">
                    <Lightning size={18} weight="fill" />
                  </div>
                  <div>
                    <h3 className="text-base font-bold text-white">Instant Solar Estimate</h3>
                    <p className="text-[11px] text-zinc-400">Calculate array capacity & net cost in 30s</p>
                  </div>
                </div>
                <button
                  onClick={reset}
                  className="rounded-full p-1.5 text-zinc-400 hover:bg-white/10 hover:text-white"
                >
                  <X size={18} />
                </button>
              </div>

              {!submitted ? (
                <div>
                  {/* Step 1: Property & Bill */}
                  {step === 1 && (
                    <div className="space-y-5">
                      <div>
                        <label className="mb-2 block text-xs font-semibold text-zinc-400 uppercase tracking-wider">
                          Property Type
                        </label>
                        <div className="grid grid-cols-2 gap-2">
                          <button
                            type="button"
                            onClick={() => setPropertyType("residential")}
                            className={`rounded-2xl border p-3 text-xs font-bold transition-all ${
                              propertyType === "residential"
                                ? "border-amber-400 bg-amber-500/20 text-amber-300"
                                : "border-white/10 bg-white/5 text-zinc-400 hover:border-white/20"
                            }`}
                          >
                            🏡 Residential
                          </button>
                          <button
                            type="button"
                            onClick={() => setPropertyType("commercial")}
                            className={`rounded-2xl border p-3 text-xs font-bold transition-all ${
                              propertyType === "commercial"
                                ? "border-amber-400 bg-amber-500/20 text-amber-300"
                                : "border-white/10 bg-white/5 text-zinc-400 hover:border-white/20"
                            }`}
                          >
                            🏢 Commercial
                          </button>
                        </div>
                      </div>

                      <div>
                        <div className="mb-2 flex justify-between text-xs text-zinc-400">
                          <span>Monthly Bill</span>
                          <span className="font-mono font-bold text-amber-400">₹{monthlyBill.toLocaleString("en-IN")}</span>
                        </div>
                        <input
                          type="range"
                          min={1000}
                          max={30000}
                          step={500}
                          value={monthlyBill}
                          onChange={(e) => setMonthlyBill(Number(e.target.value))}
                          className="h-2 w-full cursor-pointer appearance-none rounded-lg bg-zinc-800 accent-amber-500"
                        />
                      </div>

                      <Button
                        variant="accent"
                        className="w-full justify-between"
                        onClick={() => setStep(2)}
                      >
                        <span>Next Step</span>
                        <CaretRight size={16} weight="bold" />
                      </Button>
                    </div>
                  )}

                  {/* Step 2: Location Pincode */}
                  {step === 2 && (
                    <form onSubmit={handleSubmit} className="space-y-5">
                      <div>
                        <label className="mb-2 block text-xs font-semibold text-zinc-400 uppercase tracking-wider">
                          Enter Location Pincode
                        </label>
                        <input
                          type="text"
                          required
                          placeholder="e.g. 560001"
                          value={pincode}
                          onChange={(e) => setPincode(e.target.value)}
                          className="w-full rounded-2xl border border-white/20 bg-black/60 px-4 py-3 font-mono text-sm text-white placeholder-zinc-500 focus:border-amber-400 focus:outline-none"
                        />
                      </div>

                      {/* Live Calculation Preview */}
                      <div className="rounded-2xl border border-amber-400/30 bg-amber-500/10 p-4">
                        <div className="grid grid-cols-2 gap-3 text-xs">
                          <div>
                            <span className="text-zinc-400">System Size:</span>
                            <div className="font-mono font-bold text-white">{systemKw.toFixed(1)} kW</div>
                          </div>
                          <div>
                            <span className="text-zinc-400">Govt Subsidy:</span>
                            <div className="font-mono font-bold text-emerald-400">₹{subsidy.toLocaleString("en-IN")}</div>
                          </div>
                          <div>
                            <span className="text-zinc-400">Est. Net Cost:</span>
                            <div className="font-mono font-bold text-amber-300">₹{netCost.toLocaleString("en-IN")}</div>
                          </div>
                          <div>
                            <span className="text-zinc-400">Annual Savings:</span>
                            <div className="font-mono font-bold text-white">₹{annualSavings.toLocaleString("en-IN")}</div>
                          </div>
                        </div>
                      </div>

                      <div className="flex gap-2">
                        <Button variant="secondary" className="flex-1" onClick={() => setStep(1)}>
                          Back
                        </Button>
                        <Button variant="accent" type="submit" className="flex-1">
                          Lock Estimate
                        </Button>
                      </div>
                    </form>
                  )}
                </div>
              ) : (
                /* Step 3: Success Confirmation */
                <div className="py-4 text-center">
                  <CheckCircle size={48} weight="fill" className="mx-auto text-emerald-400 mb-3" />
                  <h4 className="text-lg font-bold text-white">Estimate Locked for {pincode}!</h4>
                  <p className="mt-2 text-xs leading-relaxed text-zinc-400">
                    Your calculated {systemKw.toFixed(1)} kW solar array net cost is estimated at ₹{netCost.toLocaleString("en-IN")}. Our technical team will review your roof layout.
                  </p>
                  <Button variant="accent" className="mt-6 w-full" onClick={reset}>
                    Done
                  </Button>
                </div>
              )}
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </>
  );
}
