import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { 
  ArrowRight, 
  Calendar, 
  MessageSquare, 
  Mail, 
  CheckCircle2, 
  ChevronDown, 
  ShieldCheck,
  ArrowLeft,
  Loader2
} from "lucide-react";
import { Link } from "wouter";
import { Navbar } from "@/components/layout/navbar";
import { PageBreadcrumb } from "@/components/layout/page-breadcrumb";
import { Footer } from "@/components/layout/footer";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { apiRequest } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";

const TRUST_ITEMS = [
  { title: "NDA-Ready", desc: "Standard mutual NDAs available for all sensitive project discussions." },
  { title: "Full IP Ownership", desc: "You retain 100% intellectual property rights for all delivered assets." },
  { title: "Secure Asset Handling", desc: "Enterprise-grade encryption for all brand assets and data." },
  { title: "Governance First", desc: "Structured approval workflows ensuring brand consistency at scale." }
];

const SERVICE_OPTIONS = [
  "Research, Strategy & Market Intelligence",
  "Brand & Creative Studio",
  "Growth & Performance Marketing",
  "Social & Digital Content Engine",
  "Creative AD Agency",
  "AI Content & Automation",
  "Brand Experience & Activations",
  "Retention & CRM Marketing",
  "Other"
];

export default function ContactPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showOptional, setShowOptional] = useState(false);
  const [enquiryId, setEnquiryId] = useState("");
  const [selectedServices, setSelectedServices] = useState<string[]>([]);

  const toggleService = (service: string) => {
    setSelectedServices(prev => 
      prev.includes(service) ? prev.filter(s => s !== service) : [...prev, service]
    );
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    const formData = new FormData(e.target as HTMLFormElement);
    
    try {
      const response = await apiRequest("POST", "/api/enquiries", {
        name: formData.get("name"),
        email: formData.get("email"),
        company: formData.get("company"),
        role: formData.get("role"),
        services: selectedServices,
        timeline: formData.get("timeline"),
        message: formData.get("message"),
        website: formData.get("website") || undefined,
        budget: formData.get("budget") || undefined,
        source: "contact_page",
      });
      
      const result = await response.json();
      setEnquiryId(result.id?.slice(0, 8).toUpperCase() || "STMP");
      setIsSubmitted(true);
      if (typeof window !== "undefined" && (window as any).dataLayer) {
        (window as any).dataLayer.push({
          event: "form_submission",
          form_name: "contact_page",
          form_source: "contact_page",
          selected_services: selectedServices,
        });
      }
    } catch (error) {
      toast({
        title: "Something went wrong",
        description: "Please try again or reach out via WhatsApp.",
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="min-h-screen bg-background text-foreground selection:bg-lime selection:text-black">
      <Navbar />
      <PageBreadcrumb />
      
      <main id="main-content" className="pt-4">
        <section className="container mx-auto px-6 pt-6 pb-20 lg:pb-32">
          <div className="max-w-4xl">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.6 }}
            >
              <Link href="/" className="inline-flex items-center gap-2 text-lime font-mono text-sm uppercase tracking-widest mb-6 hover:opacity-80 transition-opacity">
                  <ArrowLeft className="w-4 h-4" /> Back to Home
              </Link>
              <h1 className="text-6xl md:text-8xl font-bold font-heading tracking-tighter leading-[0.9] mb-6 uppercase">
                Contact <span className="text-lime italic">Us</span>
              </h1>
              <p className="text-lg md:text-xl text-lime font-mono tracking-[0.2em] uppercase mb-12">
                Scale Your Creative Output Now.
              </p>
              
              <p className="text-xl md:text-2xl text-muted-foreground max-w-2xl font-light leading-relaxed mb-16">
                India's first Creative Tech Lab for D2C brands. We combine strategic intelligence with hyper-scale production.
              </p>
            </motion.div>

            <div className="grid md:grid-cols-3 gap-6">
              <motion.div 
                initial={{ opacity: 0, y: 20 }} 
                animate={{ opacity: 1, y: 0 }} 
                transition={{ delay: 0.2 }}
                className="p-6 bg-white/5 border border-white/10 rounded-2xl hover:border-lime/30 transition-colors group"
              >
                <a href="https://wa.me/919916942543?text=Hi%2C%20I'd%20like%20to%20book%20a%20discovery%20call%20with%20STAMP%20SIZE." target="_blank" rel="noopener noreferrer" className="block">
                  <div className="w-12 h-12 rounded-full bg-lime/10 flex items-center justify-center mb-4 group-hover:bg-lime/20 transition-colors">
                    <Calendar className="text-lime w-6 h-6" />
                  </div>
                  <h3 className="font-heading font-bold uppercase mb-2" data-testid="text-book-call">Book a Call</h3>
                  <p className="text-sm text-muted-foreground mb-4">Message us on WhatsApp to schedule a 30-min discovery session.</p>
                  <div className="text-lime p-0 h-auto group-hover:translate-x-1 transition-transform inline-flex items-center text-sm font-medium">
                    Schedule via WhatsApp <ArrowRight className="ml-2 w-4 h-4" />
                  </div>
                </a>
              </motion.div>

              <motion.div 
                initial={{ opacity: 0, y: 20 }} 
                animate={{ opacity: 1, y: 0 }} 
                transition={{ delay: 0.3 }}
                className="p-6 bg-white/5 border border-white/10 rounded-2xl hover:border-lime/30 transition-colors group"
              >
                <a href="https://wa.me/919916942543" target="_blank" rel="noopener noreferrer" className="block">
                  <div className="w-12 h-12 rounded-full bg-lime/10 flex items-center justify-center mb-4 group-hover:bg-lime/20 transition-colors">
                    <MessageSquare className="text-lime w-6 h-6" />
                  </div>
                  <h3 className="font-heading font-bold uppercase mb-2" data-testid="text-whatsapp">WhatsApp Us</h3>
                  <p className="text-sm text-muted-foreground mb-4">Direct access to our growth team for urgent inquiries.</p>
                  <div className="text-lime p-0 h-auto group-hover:translate-x-1 transition-transform inline-flex items-center text-sm font-medium">
                    Chat Now <ArrowRight className="ml-2 w-4 h-4" />
                  </div>
                </a>
              </motion.div>

              <motion.div 
                initial={{ opacity: 0, y: 20 }} 
                animate={{ opacity: 1, y: 0 }} 
                transition={{ delay: 0.4 }}
                className="p-6 bg-white/5 border border-white/10 rounded-2xl hover:border-lime/30 transition-colors group"
              >
                <a href="mailto:hello@stampsize.in" className="block">
                  <div className="w-12 h-12 rounded-full bg-lime/10 flex items-center justify-center mb-4 group-hover:bg-lime/20 transition-colors">
                    <Mail className="text-lime w-6 h-6" />
                  </div>
                  <h3 className="font-heading font-bold uppercase mb-2" data-testid="text-email">Email Direct</h3>
                  <p className="text-sm text-muted-foreground mb-4">For partnerships, vendor inquiries, or detailed briefs.</p>
                  <div className="text-lime p-0 h-auto group-hover:translate-x-1 transition-transform inline-flex items-center text-sm font-medium">
                    hello@stampsize.in <ArrowRight className="ml-2 w-4 h-4" />
                  </div>
                </a>
              </motion.div>
            </div>
          </div>
        </section>

        <section className="bg-white/[0.02] border-y border-white/5 py-24 lg:py-32">
          <div className="container mx-auto px-6">
            <div className="grid lg:grid-cols-2 gap-20 items-start">
              
              <div>
                <AnimatePresence mode="wait">
                  {!isSubmitted ? (
                    <motion.div
                      key="form"
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: 20 }}
                    >
                      <h2 className="text-3xl md:text-5xl font-heading font-bold uppercase mb-12 tracking-tighter">Request a Pilot</h2>
                      <form onSubmit={handleSubmit} className="space-y-8">
                        <div className="grid md:grid-cols-2 gap-8">
                          <div className="space-y-2">
                            <Label htmlFor="name" className="text-xs uppercase tracking-widest text-muted-foreground">Full Name *</Label>
                            <Input id="name" name="name" required placeholder="Arjun Sharma" className="bg-white/5 border-white/10 focus:border-lime transition-all h-12" data-testid="input-contact-name" />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="email" className="text-xs uppercase tracking-widest text-muted-foreground">Work Email *</Label>
                            <Input id="email" name="email" type="email" required placeholder="arjun@brand.com" className="bg-white/5 border-white/10 focus:border-lime transition-all h-12" data-testid="input-contact-email" />
                          </div>
                        </div>

                        <div className="grid md:grid-cols-2 gap-8">
                          <div className="space-y-2">
                            <Label htmlFor="company" className="text-xs uppercase tracking-widest text-muted-foreground">Company Name *</Label>
                            <Input id="company" name="company" required placeholder="Your Brand Ltd." className="bg-white/5 border-white/10 focus:border-lime transition-all h-12" data-testid="input-contact-company" />
                          </div>
                          <div className="space-y-2">
                            <Label htmlFor="role" className="text-xs uppercase tracking-widest text-muted-foreground">Your Role *</Label>
                            <Select name="role" required>
                              <SelectTrigger className="bg-white/5 border-white/10 focus:border-lime transition-all h-12" data-testid="select-contact-role">
                                <SelectValue placeholder="Select role" />
                              </SelectTrigger>
                              <SelectContent className="bg-zinc-900 border-white/10 text-white">
                                <SelectItem value="cmo">CMO / CXO</SelectItem>
                                <SelectItem value="growth">Growth / Performance</SelectItem>
                                <SelectItem value="brand">Brand / Creative</SelectItem>
                                <SelectItem value="ecom">E-commerce</SelectItem>
                                <SelectItem value="other">Other</SelectItem>
                              </SelectContent>
                            </Select>
                          </div>
                        </div>

                        <div className="space-y-4">
                          <Label className="text-xs uppercase tracking-widest text-muted-foreground">What do you need? *</Label>
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                            {SERVICE_OPTIONS.map((item) => (
                              <div 
                                key={item} 
                                className={`flex items-center space-x-2 p-3 rounded-lg border transition-all cursor-pointer ${
                                  selectedServices.includes(item) 
                                    ? 'bg-lime/10 border-lime/30' 
                                    : 'bg-white/5 border-white/5 hover:border-lime/20'
                                }`}
                                onClick={() => toggleService(item)}
                              >
                                <Checkbox 
                                  id={item} 
                                  checked={selectedServices.includes(item)}
                                  onCheckedChange={() => toggleService(item)}
                                />
                                <label htmlFor={item} className="text-sm cursor-pointer leading-tight">{item}</label>
                              </div>
                            ))}
                          </div>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="timeline" className="text-xs uppercase tracking-widest text-muted-foreground">Timeline *</Label>
                          <Select name="timeline" required>
                            <SelectTrigger className="bg-white/5 border-white/10 focus:border-lime transition-all h-12" data-testid="select-contact-timeline">
                              <SelectValue placeholder="When do you want to start?" />
                            </SelectTrigger>
                            <SelectContent className="bg-zinc-900 border-white/10 text-white">
                              <SelectItem value="asap">ASAP</SelectItem>
                              <SelectItem value="2weeks">Within 2 weeks</SelectItem>
                              <SelectItem value="month">This month</SelectItem>
                              <SelectItem value="exploring">Just exploring</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>

                        <div className="space-y-2">
                          <Label htmlFor="message" className="text-xs uppercase tracking-widest text-muted-foreground">Brief Message *</Label>
                          <Textarea id="message" name="message" required placeholder="Tell us about your volume and pain points..." className="bg-white/5 border-white/10 focus:border-lime transition-all min-h-[120px]" data-testid="input-contact-message" />
                        </div>

                        <div className="pt-4">
                          <Button 
                            type="button" 
                            variant="ghost" 
                            className="text-lime hover:text-lime hover:bg-lime/10 px-0 flex items-center gap-2 mb-6"
                            onClick={() => setShowOptional(!showOptional)}
                          >
                            <ChevronDown className={`w-4 h-4 transition-transform ${showOptional ? 'rotate-180' : ''}`} />
                            {showOptional ? 'Hide' : 'Add'} Details (Optional)
                          </Button>

                          {showOptional && (
                            <motion.div 
                              initial={{ opacity: 0, height: 0 }}
                              animate={{ opacity: 1, height: 'auto' }}
                              className="space-y-6 overflow-hidden mb-8"
                            >
                              <div className="space-y-2">
                                <Label htmlFor="website" className="text-xs uppercase tracking-widest text-muted-foreground">Website URL</Label>
                                <Input id="website" name="website" placeholder="https://..." className="bg-white/5 border-white/10 h-12" />
                              </div>
                              <div className="space-y-2">
                                <Label htmlFor="budget" className="text-xs uppercase tracking-widest text-muted-foreground">Monthly Budget Band</Label>
                                <Select name="budget">
                                  <SelectTrigger className="bg-white/5 border-white/10 h-12">
                                    <SelectValue placeholder="Select range" />
                                  </SelectTrigger>
                                  <SelectContent className="bg-zinc-900 border-white/10 text-white">
                                    <SelectItem value="1-5">1L - 5L</SelectItem>
                                    <SelectItem value="5-20">5L - 20L</SelectItem>
                                    <SelectItem value="20plus">20L+</SelectItem>
                                    <SelectItem value="private">Prefer not to say</SelectItem>
                                  </SelectContent>
                                </Select>
                              </div>
                            </motion.div>
                          )}
                        </div>

                        <div className="flex items-start space-x-3 py-4">
                          <Checkbox id="consent" required />
                          <label htmlFor="consent" className="text-xs text-muted-foreground leading-snug cursor-pointer">
                            You may contact me about this inquiry. We value your privacy and respond within 1 business day.
                          </label>
                        </div>

                        <input type="text" name="_honeypot" className="hidden" tabIndex={-1} autoComplete="off" aria-hidden="true" />
                        <Button 
                          disabled={isSubmitting}
                          className="w-full h-14 bg-lime text-black hover:bg-lime/90 font-heading font-bold text-lg uppercase group"
                          data-testid="button-submit-contact"
                        >
                          {isSubmitting ? (
                            <><Loader2 className="w-5 h-5 mr-2 animate-spin" /> Submitting...</>
                          ) : (
                            <>Initialize Pilot <ArrowRight className="ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform" /></>
                          )}
                        </Button>
                        <div className="flex items-center justify-center gap-2 mt-3 text-[10px] text-white/30 font-mono">
                          <ShieldCheck className="w-3 h-3" />
                          <span>256-bit SSL Encrypted · DPDP Compliant · No Spam</span>
                        </div>
                      </form>
                    </motion.div>
                  ) : (
                    <motion.div
                      key="success"
                      initial={{ opacity: 0, scale: 0.9 }}
                      animate={{ opacity: 1, scale: 1 }}
                      className="text-center py-20 bg-lime/5 border border-lime/20 rounded-[40px]"
                    >
                      <CheckCircle2 className="w-20 h-20 text-lime mx-auto mb-6" />
                      <h2 className="text-4xl font-heading font-bold uppercase mb-4">Transmission Received</h2>
                      <p className="text-muted-foreground mb-8 max-w-sm mx-auto">
                        Inquiry ID: <span className="text-white font-mono">STMP-{enquiryId}</span>. Our growth team will respond within 24 hours.
                      </p>
                      <div className="flex flex-col sm:flex-row gap-4 justify-center px-6">
                        <Button className="bg-lime text-black font-bold uppercase" onClick={() => { setIsSubmitted(false); setSelectedServices([]); }}>Start New Inquiry</Button>
                        <Button variant="outline" className="border-white/20 uppercase" onClick={() => window.location.href='/'}>Back to Home</Button>
                      </div>
                    </motion.div>
                  )}
                </AnimatePresence>
              </div>

              <div className="lg:pl-10 flex items-center">
                <div className="bg-white/5 border border-white/10 rounded-[40px] p-8 md:p-12 shadow-2xl w-full">
                  <h3 className="text-sm font-mono text-lime uppercase tracking-[0.4em] mb-12 flex items-center gap-3">
                    <ShieldCheck className="w-5 h-5" />
                    Trust & Governance
                  </h3>
                  <div className="grid gap-8">
                    {TRUST_ITEMS.map((item) => (
                      <div key={item.title} className="group">
                        <h4 className="text-white font-heading font-bold uppercase tracking-tight mb-2 group-hover:text-lime transition-colors">
                          {item.title}
                        </h4>
                        <p className="text-sm text-muted-foreground leading-relaxed">
                          {item.desc}
                        </p>
                      </div>
                    ))}
                  </div>
                  <div className="mt-12 pt-8 border-t border-white/10">
                    <p className="text-[10px] text-white/20 font-mono uppercase tracking-[0.2em] leading-loose">
                      Legal framework built for high-growth enterprise scale. Ask for our full DPA / MSA documentation.
                    </p>
                  </div>
                </div>
              </div>

            </div>
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}
