import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  ArrowLeft,
  ArrowRight,
  CheckCircle2,
  Home,
  Calendar,
  PoundSterling,
  User,
  Mail,
  Phone,
  MapPin,
  Loader2,
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { ASSETS } from '@/lib/assets';
import { useSettings } from '@/lib/SettingsContext';

const STEPS = [
  { id: 'property', title: 'Property Type', subtitle: 'What kind of property do you own?', icon: Home },
  { id: 'roof', title: 'Roof Age', subtitle: 'How old is your roof?', icon: Calendar },
  { id: 'bill', title: 'Monthly Bill', subtitle: 'What is your average monthly electricity bill?', icon: PoundSterling },
  { id: 'contact', title: 'Contact Info', subtitle: 'This allows our agents to further discuss your enquiry', icon: User },
];

const propertyTypes = [
  { value: 'single_family', label: 'Detached House', desc: 'Stand-alone single family home' },
  { value: 'multi_family', label: 'Semi-Detached', desc: 'Paired with one neighbouring property' },
  { value: 'townhome', label: 'Terraced', desc: 'Row house within a terrace' },
  { value: 'commercial', label: 'Commercial', desc: 'Business or commercial property' },
];

const roofAges = [
  { value: '0-5', label: '0–5 Years', desc: 'Relatively new roof' },
  { value: '5-10', label: '5–10 Years', desc: 'Good condition' },
  { value: '10-15', label: '10–15 Years', desc: 'May need inspection' },
  { value: '15-20', label: '15–20 Years', desc: 'Consider replacement' },
  { value: '20+', label: '20+ Years', desc: 'Likely needs replacement' },
  { value: 'not_sure', label: 'Not Sure', desc: "We'll assess it during your survey" },
];

// Based on Project Solar UK figures (April 2026 Ofgem rates)
const calculateEstimate = (monthlyBill) => {
  const ofgemRate = 0.2467; // £/kWh — Ofgem April 2026
  const segRate = 0.12; // £/kWh — typical SEG export (Octopus)
  const generationFactor = 900; // kWh/kWp/yr — UK average
  const panelWattage = 0.45; // kW per panel (450W)
  const selfConsumptionRate = 0.55; // 55% used on-site

  const annualCost = monthlyBill * 12;
  const annualUsage = annualCost / ofgemRate;
  const systemSizeRaw = annualUsage / generationFactor;
  const panels = Math.ceil(systemSizeRaw / panelWattage);
  const annualGeneration = panels * panelWattage * generationFactor;
  const selfConsumed = annualGeneration * selfConsumptionRate;
  const exported = annualGeneration * (1 - selfConsumptionRate);
  const gridAvoided = selfConsumed * ofgemRate;
  const segIncome = exported * segRate;
  const annualSavings = Math.round(gridAvoided + segIncome);
  const monthlySavings = Math.round(annualSavings / 12);

  return { panels, monthlySavings, annualSavings };
};

export default function GetQuote() {
  const navigate = useNavigate();
  const { settings } = useSettings();
  const logoSrc = settings.site_logo || ASSETS.logo;
  const [currentStep, setCurrentStep] = useState(0);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [postcodeLookup, setPostcodeLookup] = useState({ loading: false, result: null, error: null });

  const urlParams = new URLSearchParams(window.location.search);
  const initialBill = urlParams.get('bill');

  const [formData, setFormData] = useState({
    property_type: '',
    roof_age: '',
    monthly_bill: initialBill ? parseInt(initialBill) : 200,
    full_name: '',
    email: '',
    phone: '',
    zip_code: '',
    address_line: '',
    town: '',
    after_hours_contact: false,
    // Honeypot: must stay empty. Bots that auto-fill every field will trip it.
    company_website: '',
  });

  const updateField = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const lookupPostcode = async () => {
    const postcode = formData.zip_code.trim();
    if (!postcode || postcode.length < 5) return;

    setPostcodeLookup({ loading: true, result: null, error: null });

    try {
      const res = await fetch(`https://api.postcodes.io/postcodes/${encodeURIComponent(postcode)}`);
      const data = await res.json();

      if (data.status === 200 && data.result) {
        const r = data.result;
        const town = r.admin_district || r.parish || r.region || '';
        setPostcodeLookup({ loading: false, result: r, error: null });
        updateField('town', town);
      } else {
        setPostcodeLookup({ loading: false, result: null, error: 'Postcode not found — please check and try again' });
      }
    } catch (err) {
      setPostcodeLookup({ loading: false, result: null, error: 'Unable to look up postcode' });
    }
  };

  const canProceed = () => {
    switch (currentStep) {
      case 0: return !!formData.property_type;
      case 1: return !!formData.roof_age;
      case 2: return formData.monthly_bill >= 50;
      case 3: return formData.full_name && formData.email && formData.phone && formData.zip_code && formData.address_line;
      default: return false;
    }
  };

  const handleNext = () => {
    if (currentStep < STEPS.length - 1) {
      setCurrentStep(prev => prev + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 0) {
      setCurrentStep(prev => prev - 1);
    }
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);

    // Honeypot: if the hidden field is filled, it's almost certainly a bot.
    // Show the normal success screen so the bot can't tell it was blocked,
    // but don't create a lead or send mail.
    if (formData.company_website) {
      setIsSubmitting(false);
      setSubmitted(true);
      return;
    }

    const { panels, monthlySavings } = calculateEstimate(formData.monthly_bill);

    const now = new Date();
    const ymd = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
    const rand = Math.random().toString(36).substring(2, 6).toUpperCase();
    const refNum = `SCU-${ymd}-${rand}`;

    // Strip the honeypot before sending real data.
    const { company_website, ...leadData } = formData;

    await base44.entities.Lead.create({
      ...leadData,
      company_website, // sent so the server can also reject bots
      panel_count: panels,
      estimated_savings: monthlySavings,
      reference_number: refNum,
      status: 'new',
    });
    // The enquiry notification email is sent server-side on lead creation
    // (recipient configured via MAIL_APPOINTMENTS_ADDRESS in .env).

    setIsSubmitting(false);
    setSubmitted(true);
  };

  const bgLightness = 7 + currentStep * 2;

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center p-6" style={{ background: `hsl(160, 50%, 12%)` }}>
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="max-w-md w-full text-center"
        >
          <div className="w-20 h-20 rounded-full bg-primary/20 border border-primary/40 flex items-center justify-center mx-auto mb-8 animate-glow-pulse">
            <CheckCircle2 className="w-10 h-10 text-primary" />
          </div>
          <h1 className="font-heading font-black text-3xl text-foreground mb-4">
            Enquiry <span className="text-primary">Submitted</span>
          </h1>
          <p className="text-muted-foreground leading-relaxed mb-8">
            Thank you for your enquiry. Our team will review your details and one of our agents will be in touch to further discuss your enquiry within 24 hours.
          </p>
          <Link to="/">
            <Button variant="outline" className="border-border/50 text-foreground hover:border-primary/50">
              <ArrowLeft className="mr-2 w-4 h-4" />
              Back to Home
            </Button>
          </Link>
        </motion.div>
      </div>
    );
  }

  return (
    <div
      className="min-h-screen flex flex-col transition-colors duration-700"
      style={{ background: `hsl(160, 50%, ${bgLightness}%)` }}
    >
      {/* Header */}
      <div className="flex items-center justify-between px-6 lg:px-10 py-6">
        <Link to="/" className="flex items-center group">
          <img
            src={logoSrc}
            alt="SolarConnectUK"
            className="h-16 w-auto group-hover:opacity-90 transition-opacity"
            style={settings.site_logo ? undefined : { mixBlendMode: 'screen', filter: 'hue-rotate(-20deg) saturate(1.2)' }}
          />
        </Link>

        <div className="flex items-center gap-3">
          {STEPS.map((_, i) => (
            <div
              key={i}
              className={`h-1 rounded-full transition-all duration-500 ${
                i <= currentStep ? 'w-8 bg-primary' : 'w-4 bg-border/50'
              }`}
            />
          ))}
        </div>

        <span className="font-mono text-xs text-muted-foreground/60 tracking-wider">
          {currentStep + 1}/{STEPS.length}
        </span>
      </div>

      {/* Content */}
      <div className="flex-1 flex items-center justify-center px-6">
        <div className="max-w-lg w-full">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentStep}
              initial={{ opacity: 0, x: 40 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -40 }}
              transition={{ duration: 0.3 }}
            >
              <span className="font-mono text-xs tracking-[0.3em] uppercase text-accent mb-3 block">
                // Step {String(currentStep + 1).padStart(2, '0')}
              </span>
              <h2 className="font-heading font-black text-3xl lg:text-4xl text-foreground mb-2">
                {STEPS[currentStep].title}
              </h2>
              <p className="text-muted-foreground mb-10">{STEPS[currentStep].subtitle}</p>

              {/* Step 0: Property Type */}
              {currentStep === 0 && (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {propertyTypes.map(pt => (
                    <button
                      key={pt.value}
                      onClick={() => updateField('property_type', pt.value)}
                      className={`text-left p-5 rounded-xl border transition-all duration-300 ${
                        formData.property_type === pt.value
                          ? 'border-primary bg-primary/10'
                          : 'border-border/30 bg-card/30 hover:border-border'
                      }`}
                    >
                      <p className="font-medium text-foreground text-sm">{pt.label}</p>
                      <p className="text-xs text-muted-foreground mt-1">{pt.desc}</p>
                    </button>
                  ))}
                </div>
              )}

              {/* Step 1: Roof Age */}
              {currentStep === 1 && (
                <div className="space-y-3">
                  {roofAges.map(ra => (
                    <button
                      key={ra.value}
                      onClick={() => updateField('roof_age', ra.value)}
                      className={`w-full text-left p-5 rounded-xl border transition-all duration-300 flex items-center justify-between ${
                        formData.roof_age === ra.value
                          ? 'border-primary bg-primary/10'
                          : 'border-border/30 bg-card/30 hover:border-border'
                      }`}
                    >
                      <div>
                        <p className="font-medium text-foreground text-sm">{ra.label}</p>
                        <p className="text-xs text-muted-foreground mt-0.5">{ra.desc}</p>
                      </div>
                      {formData.roof_age === ra.value && (
                        <CheckCircle2 className="w-5 h-5 text-primary flex-shrink-0" />
                      )}
                    </button>
                  ))}
                </div>
              )}

              {/* Step 2: Monthly Bill */}
              {currentStep === 2 && (
                <div className="space-y-8">
                  <div className="text-center">
                    <span className="font-mono text-6xl font-bold text-primary">
                      £{formData.monthly_bill}
                    </span>
                    <p className="text-xs text-muted-foreground tracking-wider uppercase mt-2">per month</p>
                  </div>
                  <div>
                    <input
                      type="range"
                      min={50}
                      max={800}
                      step={10}
                      value={formData.monthly_bill}
                      onChange={(e) => updateField('monthly_bill', parseInt(e.target.value))}
                      className="w-full accent-[hsl(160,84%,39%)] h-2 rounded-full appearance-none cursor-pointer bg-border/50"
                      aria-label="Monthly electricity bill"
                      aria-valuenow={formData.monthly_bill}
                      aria-valuetext={`£${formData.monthly_bill} per month`}
                    />
                    <div className="flex justify-between mt-2">
                      <span className="font-mono text-xs text-muted-foreground/60">£50</span>
                      <span className="font-mono text-xs text-muted-foreground/60">£800</span>
                    </div>
                  </div>
                </div>
              )}

              {/* Step 3: Contact Info */}
              {currentStep === 3 && (
                <div className="space-y-5">
                  {/* Honeypot — hidden from real users, off-screen and excluded
                      from tab order. Bots that fill every field will populate it. */}
                  <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', width: '1px', height: '1px', overflow: 'hidden' }}>
                    <label htmlFor="company_website">Company website (leave blank)</label>
                    <input
                      id="company_website"
                      name="company_website"
                      type="text"
                      tabIndex={-1}
                      autoComplete="off"
                      value={formData.company_website}
                      onChange={e => updateField('company_website', e.target.value)}
                    />
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground tracking-wider uppercase mb-2 block">Full Name</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
                      <Input
                        placeholder="John Doe"
                        value={formData.full_name}
                        onChange={e => updateField('full_name', e.target.value)}
                        className="pl-10 bg-card/30 border-border/30 h-12 text-foreground placeholder:text-muted-foreground/30"
                      />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground tracking-wider uppercase mb-2 block">Email</Label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
                      <Input
                        type="email"
                        placeholder="john@example.com"
                        value={formData.email}
                        onChange={e => updateField('email', e.target.value)}
                        className="pl-10 bg-card/30 border-border/30 h-12 text-foreground placeholder:text-muted-foreground/30"
                      />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground tracking-wider uppercase mb-2 block">Phone</Label>
                    <div className="relative">
                      <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
                      <Input
                        type="tel"
                        placeholder="07700 900000"
                        value={formData.phone}
                        onChange={e => updateField('phone', e.target.value)}
                        className="pl-10 bg-card/30 border-border/30 h-12 text-foreground placeholder:text-muted-foreground/30"
                      />
                    </div>
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground tracking-wider uppercase mb-2 block">Postcode</Label>
                    <div className="relative">
                      <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
                      <Input
                        placeholder="SW1A 1AA"
                        value={formData.zip_code}
                        onChange={e => {
                          updateField('zip_code', e.target.value.toUpperCase());
                          if (postcodeLookup.result || postcodeLookup.error) {
                            setPostcodeLookup({ loading: false, result: null, error: null });
                          }
                        }}
                        onBlur={lookupPostcode}
                        className="pl-10 pr-10 bg-card/30 border-border/30 h-12 text-foreground placeholder:text-muted-foreground/30 uppercase"
                      />
                      {postcodeLookup.loading && (
                        <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-primary animate-spin" />
                      )}
                    </div>
                    {postcodeLookup.result && (
                      <div className="mt-2 flex items-center gap-2 text-xs text-primary">
                        <CheckCircle2 className="w-4 h-4 flex-shrink-0" />
                        <span>{postcodeLookup.result.admin_district || postcodeLookup.result.parish}, {postcodeLookup.result.country}</span>
                      </div>
                    )}
                    {postcodeLookup.error && (
                      <p className="mt-2 text-xs text-destructive">{postcodeLookup.error}</p>
                    )}
                  </div>
                  <div>
                    <Label className="text-xs text-muted-foreground tracking-wider uppercase mb-2 block">Address Line</Label>
                    <div className="relative">
                      <Home className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground/40" />
                      <Input
                        placeholder="123 High Street"
                        value={formData.address_line}
                        onChange={e => updateField('address_line', e.target.value)}
                        className="pl-10 bg-card/30 border-border/30 h-12 text-foreground placeholder:text-muted-foreground/30"
                      />
                    </div>
                    {formData.town && (
                      <p className="mt-2 text-xs text-muted-foreground/70 ml-1">{formData.town}</p>
                    )}
                  </div>
                  <label className="flex items-start gap-3 rounded-xl border border-border/30 bg-card/30 p-4 cursor-pointer hover:border-primary/40 transition-colors">
                    <Checkbox
                      checked={formData.after_hours_contact}
                      onCheckedChange={v => updateField('after_hours_contact', !!v)}
                      className="mt-0.5"
                    />
                    <span className="text-sm text-muted-foreground leading-relaxed">
                      I'm happy to be contacted outside normal working hours (evenings and weekends, at reasonable times).
                    </span>
                  </label>
                </div>
              )}
            </motion.div>
          </AnimatePresence>
        </div>
      </div>

      {/* Navigation */}
      <div className="px-6 lg:px-10 py-8">
        <div className="max-w-lg mx-auto flex items-center justify-between">
          <Button
            variant="ghost"
            onClick={currentStep === 0 ? () => navigate('/') : handleBack}
            className="text-muted-foreground hover:text-foreground"
          >
            <ArrowLeft className="mr-2 w-4 h-4" />
            {currentStep === 0 ? 'Home' : 'Back'}
          </Button>

          {currentStep < STEPS.length - 1 ? (
            <Button
              onClick={handleNext}
              disabled={!canProceed()}
              className="bg-primary text-primary-foreground hover:bg-primary/90 font-semibold px-8 disabled:opacity-30"
            >
              Continue
              <ArrowRight className="ml-2 w-4 h-4" />
            </Button>
          ) : (
            <Button
              onClick={handleSubmit}
              disabled={!canProceed() || isSubmitting}
              className="bg-primary text-primary-foreground hover:bg-primary/90 font-semibold px-8 disabled:opacity-30"
            >
              {isSubmitting ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : null}
              {isSubmitting ? 'Submitting...' : 'Send My Enquiry'}
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}