"use client";

import { useState } from "react";
import { motion } from "framer-motion";
import { Calculator, CheckCircle2, Clock, Truck, ShieldCheck, ArrowRight, Sparkles } from "lucide-react";
import { SectionHeading } from "./section-heading";
import { Button } from "@/components/ui/button";

type DomainKey = "civil" | "energy" | "roads" | "buildings" | "water" | "survey";

interface DomainConfig {
  label: string;
  defaultTime: string;
  execTime: string;
  equipment: string[];
  deliverables: string[];
  regulatory: string[];
}

const DOMAIN_DATA: Record<DomainKey, DomainConfig> = {
  civil: {
    label: "Civil & Structural Engineering",
    defaultTime: "3 – 5 Weeks",
    execTime: "6 – 14 Months",
    equipment: ["Excavators", "Concrete Mixers", "Tower Crane", "Batching Plant"],
    deliverables: [
      "Substructure & Foundation Design",
      "Structural Analysis & Bar Bending Schedule",
      "Quality Assurance & Test Certificates",
    ],
    regulatory: ["Office of Company Registrar", "Local Municipality Building Permit"],
  },
  energy: {
    label: "Hydropower & Energy Infrastructure",
    defaultTime: "6 – 10 Weeks",
    execTime: "12 – 28 Months",
    equipment: ["Heavy Excavators", "Rock Drills", "Crane Trucks", "High-Tension Line Pullers"],
    deliverables: [
      "Penstock & Weir Structural DPR",
      "Substation Grid Connection Layout",
      "EIA / IEE Environmental Clearance",
    ],
    regulatory: ["Department of Electricity Development (DoED)", "Ministry of Forests & Environment"],
  },
  roads: {
    label: "Roads, Highways & Bridges",
    defaultTime: "4 – 6 Weeks",
    execTime: "8 – 20 Months",
    equipment: ["Bulldozers", "Asphalt Pavers", "Road Rollers", "Backhoe Loaders"],
    deliverables: [
      "Topographic Route Alignment Map",
      "Pavement Thickness Design & Material Specs",
      "Drainage & Gabion Retaining Wall Plan",
    ],
    regulatory: ["Department of Roads (DoR)", "Local Infrastructure Office"],
  },
  buildings: {
    label: "Residential & Commercial Buildings",
    defaultTime: "2 – 4 Weeks",
    execTime: "5 – 12 Months",
    equipment: ["Tower Crane", "Concrete Pumps", "Scaffolding Systems"],
    deliverables: [
      "Architectural 3D Renderings & Floor Plans",
      "Seismic Analysis & Structural Design",
      "Interior & HVAC Electrical Layout",
    ],
    regulatory: ["Kathmandu Valley Development Authority (KVDA)", "Local Municipality"],
  },
  water: {
    label: "Water Supply & Wastewater",
    defaultTime: "3 – 5 Weeks",
    execTime: "6 – 15 Months",
    equipment: ["Trench Excavators", "Pipe Laying Cranes", "Water Pumps"],
    deliverables: [
      "Hydraulic Network Modeling",
      "WTP / STP Plant Structural Blueprint",
      "Water Quality Analysis Report",
    ],
    regulatory: ["Department of Water Supply & Sewerage Management (DWSSM)"],
  },
  survey: {
    label: "Topographic Survey & GIS Mapping",
    defaultTime: "1 – 2 Weeks",
    execTime: "2 – 6 Weeks",
    equipment: ["DGPS / RTK Rovers", "Total Stations", "GIS Workstations"],
    deliverables: [
      "3D Digital Elevation Model (DEM)",
      "High-Precision Contour AutoCAD Drawings",
      "Spatial GIS Database & Boundary Reports",
    ],
    regulatory: ["Survey Department, Ministry of Land Management"],
  },
};

export function ProjectEstimator() {
  const [selectedDomain, setSelectedDomain] = useState<DomainKey>("civil");
  const [scale, setScale] = useState<"small" | "medium" | "large">("medium");
  const [selectedServices, setSelectedServices] = useState<string[]>([
    "Detailed Project Report (DPR)",
    "Turnkey Construction",
  ]);

  const config = DOMAIN_DATA[selectedDomain];

  const toggleService = (srv: string) => {
    if (selectedServices.includes(srv)) {
      setSelectedServices(selectedServices.filter((s) => s !== srv));
    } else {
      setSelectedServices([...selectedServices, srv]);
    }
  };

  const getEstimatedScaleMultiplier = () => {
    if (scale === "small") return "Phase 1 / Community Scope";
    if (scale === "medium") return "Regional / Commercial Scope";
    return "Major Infrastructure / Capital Scope";
  };

  const handleSendToContact = () => {
    const summary = `Project Scope Inquiry:\nDomain: ${config.label}\nScale: ${getEstimatedScaleMultiplier()}\nRequired Services: ${selectedServices.join(
      ", "
    )}`;
    
    // Pass summary to form textarea via url or state dispatch
    const contactElem = document.getElementById("contact");
    const textarea = document.getElementById("message") as HTMLTextAreaElement | null;
    if (textarea) {
      textarea.value = summary;
      textarea.dispatchEvent(new Event("input", { bubbles: true }));
    }
    if (contactElem) {
      contactElem.scrollIntoView({ behavior: "smooth" });
    }
  };

  return (
    <section id="estimator" className="section-pad bg-muted/30">
      <div className="mx-auto max-w-7xl px-4 md:px-6">
        <SectionHeading
          eyebrow="Interactive Utility"
          title="Project scope & planning estimator"
          description="Configure your infrastructure parameters to preview recommended engineering deliverables, estimated timelines, and required equipment fleet."
        />

        <div className="mt-12 grid gap-8 lg:grid-cols-12">
          {/* Controls Column */}
          <div className="lg:col-span-7 space-y-6">
            {/* Step 1: Select Domain */}
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <label className="text-xs font-bold uppercase tracking-wider text-primary flex items-center gap-2">
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] text-primary-foreground font-extrabold">1</span>
                Select Infrastructure Category
              </label>
              <div className="mt-4 grid gap-2.5 sm:grid-cols-2">
                {(Object.keys(DOMAIN_DATA) as DomainKey[]).map((key) => {
                  const active = selectedDomain === key;
                  return (
                    <button
                      key={key}
                      onClick={() => setSelectedDomain(key)}
                      className={`flex items-center justify-between rounded-lg border p-3.5 text-left text-xs font-semibold transition-all duration-200 ${
                        active
                          ? "border-primary bg-primary/10 text-foreground shadow-sm"
                          : "border-border bg-background/50 text-muted-foreground hover:border-primary/40 hover:text-foreground"
                      }`}
                    >
                      <span>{DOMAIN_DATA[key].label}</span>
                      {active && <CheckCircle2 className="h-4 w-4 text-primary shrink-0 ml-2" />}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Step 2: Select Scale */}
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <label className="text-xs font-bold uppercase tracking-wider text-primary flex items-center gap-2">
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] text-primary-foreground font-extrabold">2</span>
                Project Scale & Complexity
              </label>
              <div className="mt-4 grid grid-cols-3 gap-3">
                {[
                  { key: "small", label: "Small / Feasibility", desc: "Local scope" },
                  { key: "medium", label: "Medium / Standard", desc: "Regional scope" },
                  { key: "large", label: "Major Infrastructure", desc: "National scope" },
                ].map((item) => {
                  const active = scale === item.key;
                  return (
                    <button
                      key={item.key}
                      onClick={() => setScale(item.key as any)}
                      className={`flex flex-col items-center justify-center rounded-lg border p-3 text-center transition-all ${
                        active
                          ? "border-primary bg-primary text-primary-foreground font-bold shadow-md shadow-primary/20"
                          : "border-border bg-background/50 text-muted-foreground hover:border-primary/40"
                      }`}
                    >
                      <span className="text-xs">{item.label}</span>
                      <span className={`text-[10px] ${active ? "text-primary-foreground/80" : "text-muted-foreground"}`}>
                        {item.desc}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Step 3: Required Engineering Scope */}
            <div className="rounded-xl border border-border bg-card p-6 shadow-sm">
              <label className="text-xs font-bold uppercase tracking-wider text-primary flex items-center gap-2">
                <span className="flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] text-primary-foreground font-extrabold">3</span>
                Scope of Work Needed
              </label>
              <div className="mt-4 flex flex-wrap gap-2">
                {[
                  "Pre-Feasibility Study",
                  "Detailed Project Report (DPR)",
                  "EIA / IEE Study",
                  "Turnkey Construction",
                  "Heavy Equipment Rental",
                  "Survey & GIS Mapping",
                ].map((srv) => {
                  const active = selectedServices.includes(srv);
                  return (
                    <button
                      key={srv}
                      onClick={() => toggleService(srv)}
                      className={`rounded-md border px-3.5 py-2 text-xs font-medium transition-all ${
                        active
                          ? "border-primary bg-primary/15 text-primary font-semibold"
                          : "border-border bg-background/50 text-muted-foreground hover:border-primary/30"
                      }`}
                    >
                      {active ? "✓ " : "+ "}
                      {srv}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Results Summary Column */}
          <div className="lg:col-span-5">
            <motion.div
              key={selectedDomain + scale}
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              className="sticky top-24 flex flex-col rounded-xl border border-border bg-card p-6 shadow-xl"
            >
              <div className="flex items-center justify-between border-b border-border pb-4">
                <div className="flex items-center gap-2">
                  <Calculator className="h-5 w-5 text-primary" />
                  <span className="text-sm font-bold text-foreground">Estimated Blueprint</span>
                </div>
                <span className="inline-flex items-center gap-1 rounded bg-amber-400/20 px-2 py-0.5 text-[11px] font-bold text-amber-500">
                  <Sparkles className="h-3 w-3" />
                  BECS Estimate
                </span>
              </div>

              {/* Timelines */}
              <div className="mt-5 grid grid-cols-2 gap-3 rounded-lg bg-muted/60 p-3.5">
                <div>
                  <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
                    <Clock className="h-3.5 w-3.5 text-primary" />
                    Study & DPR Phase
                  </div>
                  <div className="mt-1 text-sm font-extrabold text-foreground">{config.defaultTime}</div>
                </div>
                <div>
                  <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
                    <Clock className="h-3.5 w-3.5 text-primary" />
                    Construction Stage
                  </div>
                  <div className="mt-1 text-sm font-extrabold text-foreground">{config.execTime}</div>
                </div>
              </div>

              {/* Recommended Deliverables */}
              <div className="mt-5">
                <div className="text-xs font-bold text-foreground uppercase tracking-wider">
                  Recommended Core Deliverables
                </div>
                <ul className="mt-2 space-y-1.5">
                  {config.deliverables.map((item) => (
                    <li key={item} className="flex items-start gap-2 text-xs text-muted-foreground">
                      <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0 text-primary" />
                      <span>{item}</span>
                    </li>
                  ))}
                </ul>
              </div>

              {/* Recommended Fleet */}
              <div className="mt-5">
                <div className="flex items-center gap-1.5 text-xs font-bold text-foreground uppercase tracking-wider">
                  <Truck className="h-4 w-4 text-primary" />
                  In-House Fleet Deployment
                </div>
                <div className="mt-2 flex flex-wrap gap-1.5">
                  {config.equipment.map((eq) => (
                    <span key={eq} className="rounded bg-muted px-2 py-1 text-[11px] font-medium text-foreground">
                      {eq}
                    </span>
                  ))}
                </div>
              </div>

              {/* Compliance Note */}
              <div className="mt-5 rounded-lg border border-primary/20 bg-primary/5 p-3 text-[11px] text-muted-foreground">
                <div className="flex items-center gap-1.5 font-bold text-foreground">
                  <ShieldCheck className="h-4 w-4 text-primary" />
                  Regulatory Compliance Covered
                </div>
                <div className="mt-1">{config.regulatory.join(" · ")}</div>
              </div>

              {/* CTA */}
              <Button onClick={handleSendToContact} size="lg" className="mt-6 w-full h-11 text-sm font-semibold">
                Generate Formal RFQ Quote
                <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </motion.div>
          </div>
        </div>
      </div>
    </section>
  );
}
