"use client";

import { useMemo, useState, useTransition } from "react";
import Link from "next/link";
import Fuse from "fuse.js";
import { Check, ChevronsUpDown, Calculator, ArrowRight } from "lucide-react";
import { motion, useMotionValue, useTransform, animate } from "motion/react";
import { useEffect } from "react";
import { cn } from "@/lib/utils";
import { NAF_CODES } from "@/data/simulateur/sectors";
import { CalButton } from "@/components/cal-button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  calculateExemption,
  formatEuros,
} from "@/lib/simulateur/calculate-exemption";
import { trackEvent } from "@/lib/analytics";
import type { NafCode, SimulateurResult } from "@/lib/simulateur/types";

// Fuse index pour l'autocomplete NAF (mêmes options que step-1-sector)
const fuseIndex = new Fuse(NAF_CODES, {
  keys: [
    { name: "code", weight: 0.4 },
    { name: "label", weight: 0.4 },
    { name: "searchTerms", weight: 0.2 },
  ],
  threshold: 0.35,
  includeScore: true,
});

function AnimatedAmount({ value }: { value: number }) {
  const count = useMotionValue(0);
  const display = useTransform(count, (v) => formatEuros(v));

  useEffect(() => {
    const controls = animate(count, value, {
      duration: 1.1,
      ease: "easeOut",
    });
    return () => controls.stop();
  }, [value, count]);

  return <motion.span>{display}</motion.span>;
}

export function MiniSimulateurHome() {
  const [nafOpen, setNafOpen] = useState(false);
  const [nafQuery, setNafQuery] = useState("");
  const [selectedNaf, setSelectedNaf] = useState<NafCode | null>(null);
  const [mwhInput, setMwhInput] = useState("");
  const [result, setResult] = useState<SimulateurResult | null>(null);
  const [isPending, startTransition] = useTransition();

  const searchResults = useMemo(() => {
    if (!nafQuery.trim()) return NAF_CODES.slice(0, 20);
    return fuseIndex
      .search(nafQuery, { limit: 20 })
      .map((r) => r.item);
  }, [nafQuery]);

  const mwh = parseFloat(mwhInput);
  const canSubmit = selectedNaf !== null && Number.isFinite(mwh) && mwh > 0;

  const handleSubmit = () => {
    if (!canSubmit || !selectedNaf) return;
    startTransition(() => {
      const r = calculateExemption({
        nafCode: selectedNaf.code,
        annualConsumptionMWh: mwh,
        hasISO50001: false,
        isOnCarbonLeakageList: null,
      });
      setResult(r);
      trackEvent("simulateur_home_mini_submit", {
        naf: selectedNaf.code,
        mwh: String(mwh),
        savingsMax: String(Math.round(r.savingsRange.max)),
      });
    });
  };

  const wizardHref = selectedNaf
    ? `/outils/simulateur-exoneration-accise-electricite/?naf=${encodeURIComponent(
        selectedNaf.code,
      )}${mwh > 0 ? `&mwh=${mwh}` : ""}`
    : "/outils/simulateur-exoneration-accise-electricite/";

  return (
    <section className="bg-orange-50/40 py-16 sm:py-24">
      <div className="mx-auto max-w-5xl px-4 sm:px-6">
        <div className="mx-auto mb-10 max-w-2xl text-center">
          <p className="mb-3 text-sm font-semibold uppercase tracking-wide text-orange-700">
            Outil gratuit — 30 secondes
          </p>
          <h2 className="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">
            Estimez vos économies d&apos;accise sur l&apos;électricité
          </h2>
          <p className="mt-3 text-base text-gray-600 sm:text-lg">
            Taux réduits 2026 de 0 à 12&nbsp;€/MWh selon votre activité.
            Calcul basé sur les taux officiels CIBS&nbsp;— arrêté du
            18/12/2025.
          </p>
        </div>

        <div className="mx-auto max-w-3xl overflow-hidden rounded-2xl bg-white p-6 shadow-lg ring-1 ring-gray-200 sm:p-10">
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            {/* Input 1 : code NAF */}
            <div>
              <label
                htmlFor="mini-naf"
                className="mb-1.5 block text-sm font-medium text-gray-900"
              >
                Votre activité (code NAF)
              </label>
              <Popover open={nafOpen} onOpenChange={setNafOpen}>
                <PopoverTrigger asChild>
                  <button
                    id="mini-naf"
                    type="button"
                    aria-expanded={nafOpen}
                    aria-haspopup="listbox"
                    className={cn(
                      "flex h-12 w-full items-center justify-between rounded-xl border bg-white px-4 text-left text-sm shadow-sm transition-colors",
                      "hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-orange-500/20",
                      selectedNaf
                        ? "border-gray-300 text-gray-900"
                        : "border-gray-300 text-gray-500",
                    )}
                  >
                    <span className="truncate">
                      {selectedNaf
                        ? `${selectedNaf.code} — ${selectedNaf.label}`
                        : "Rechercher activité ou code NAF..."}
                    </span>
                    <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 text-gray-400" />
                  </button>
                </PopoverTrigger>
                <PopoverContent
                  className="w-[min(520px,calc(100vw-2rem))] p-0"
                  align="start"
                >
                  <Command shouldFilter={false}>
                    <CommandInput
                      placeholder="Ex : fonderie, 24.10Z, data center..."
                      value={nafQuery}
                      onValueChange={setNafQuery}
                    />
                    <CommandList>
                      <CommandEmpty>Aucun code NAF trouvé.</CommandEmpty>
                      <CommandGroup>
                        {searchResults.map((naf) => (
                          <CommandItem
                            key={naf.code}
                            value={naf.code}
                            onSelect={() => {
                              setSelectedNaf(naf);
                              setNafOpen(false);
                              setNafQuery("");
                            }}
                          >
                            <Check
                              className={cn(
                                "mr-2 h-4 w-4",
                                selectedNaf?.code === naf.code
                                  ? "opacity-100"
                                  : "opacity-0",
                              )}
                            />
                            <div className="flex flex-col">
                              <span className="font-medium">{naf.code}</span>
                              <span className="text-xs text-gray-500">
                                {naf.label}
                              </span>
                            </div>
                          </CommandItem>
                        ))}
                      </CommandGroup>
                    </CommandList>
                  </Command>
                </PopoverContent>
              </Popover>
            </div>

            {/* Input 2 : MWh */}
            <div>
              <label
                htmlFor="mini-mwh"
                className="mb-1.5 block text-sm font-medium text-gray-900"
              >
                Consommation annuelle
              </label>
              <div className="relative">
                <input
                  id="mini-mwh"
                  type="number"
                  min={0}
                  step="any"
                  inputMode="decimal"
                  value={mwhInput}
                  onChange={(e) => setMwhInput(e.target.value)}
                  placeholder="Ex : 2 500"
                  className="h-12 w-full rounded-xl border border-gray-300 bg-white px-4 pr-16 text-sm shadow-sm placeholder:text-gray-400 focus:border-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500/20"
                />
                <span className="pointer-events-none absolute inset-y-0 right-4 flex items-center text-sm text-gray-500">
                  MWh
                </span>
              </div>
            </div>
          </div>

          <div className="mt-6 flex justify-end">
            <button
              type="button"
              disabled={!canSubmit || isPending}
              onClick={handleSubmit}
              className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-orange-600 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-orange-800 focus:outline-none focus:ring-2 focus:ring-orange-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-40 sm:w-auto"
            >
              <Calculator size={18} />
              {isPending ? "Calcul..." : "Estimer mes économies"}
            </button>
          </div>

          {/* Résultat */}
          {result && (
            <motion.div
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.35, ease: "easeOut" }}
              className="mt-8 rounded-xl border border-orange-200 bg-orange-50 p-6"
            >
              {result.isEligible && result.savingsRange.max > 0 ? (
                <>
                  <p className="text-sm font-medium uppercase tracking-wide text-orange-700">
                    Économies annuelles estimées
                  </p>
                  <p className="mt-2 text-4xl font-extrabold text-orange-700 sm:text-5xl">
                    <AnimatedAmount value={result.savingsRange.max} />
                    <span className="ml-2 text-base font-medium text-gray-600 sm:text-lg">
                      / an
                    </span>
                  </p>
                  {result.savingsRange.min !== result.savingsRange.max && (
                    <p className="mt-1 text-sm text-gray-600">
                      Fourchette selon profil&nbsp;:{" "}
                      <span className="font-semibold text-gray-900">
                        {formatEuros(result.savingsRange.min)}
                      </span>{" "}
                      –{" "}
                      <span className="font-semibold text-gray-900">
                        {formatEuros(result.savingsRange.max)}
                      </span>
                    </p>
                  )}
                  <p className="mt-1 text-sm text-gray-600">
                    Remboursement rétroactif potentiel sur 2 ans :{" "}
                    <span className="font-semibold text-gray-900">
                      {formatEuros(result.twoYearRetroactiveSavings)}
                    </span>
                  </p>

                  <div className="mt-5 flex flex-col gap-3 sm:flex-row">
                    <Link
                      href={wizardHref}
                      className="inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-gray-800"
                    >
                      Affiner mon estimation gratuite
                      <ArrowRight size={16} />
                    </Link>
                    <CalButton
                      variant="secondary"
                      location="home_mini_simulateur_eligible"
                      className="rounded-xl border border-gray-300 bg-white px-6 py-3 text-sm font-semibold text-gray-900 shadow-sm transition-colors hover:bg-gray-50"
                    >
                      Parler à un expert
                    </CalButton>
                  </div>
                </>
              ) : (
                <>
                  <p className="text-sm font-medium text-gray-900">
                    Aucune exonération évidente à ce stade.
                  </p>
                  <p className="mt-1 text-sm text-gray-600">
                    Certaines situations (électro-intensité, procédés, fuite de
                    carbone) ne sont détectables qu&apos;avec le diagnostic
                    complet. Un expert peut analyser votre cas en 15 minutes.
                  </p>
                  <div className="mt-4 flex flex-col gap-3 sm:flex-row">
                    <Link
                      href={wizardHref}
                      className="inline-flex items-center justify-center gap-2 rounded-xl bg-gray-900 px-6 py-3 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-gray-800"
                    >
                      Lancer le diagnostic complet
                      <ArrowRight size={16} />
                    </Link>
                    <CalButton
                      variant="secondary"
                      location="home_mini_simulateur_zero"
                      className="rounded-xl border border-gray-300 bg-white px-6 py-3 text-sm font-semibold text-gray-900 shadow-sm transition-colors hover:bg-gray-50"
                    >
                      Parler à un expert
                    </CalButton>
                  </div>
                </>
              )}
            </motion.div>
          )}
        </div>
      </div>
    </section>
  );
}
