"use client";

import { useState } from "react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/app/shadcn_components/ui/popover";
import { ChevronDown, Check, Search } from "lucide-react";
import type { ScenarioSummary } from "../types";

export type ReportView = "current-stock" | "recommended" | number;

const GOAL_SHORT: Record<string, string> = {
  "Increasing EPC": "Target EPC",
  "Reducing CO2 emissions": "Reducing CO₂",
  "Energy Savings": "Energy savings",
  "Valuation Improvement": "Valuation",
};

function scenarioGoalLine(s: ScenarioSummary): string {
  const goal = s.goal ? (GOAL_SHORT[s.goal] ?? s.goal) : "";
  const target =
    s.goal === "Increasing EPC" && s.goalValue ? ` ${s.goalValue}` : "";
  const budget = s.budget ? ` · £${(s.budget / 1000).toFixed(0)}k/home` : "";
  return `${goal}${target}${budget}`.trim();
}

export function ScenarioCombobox({
  scenarios,
  value,
  onChange,
}: {
  scenarios: ScenarioSummary[];
  value: ReportView;
  onChange: (v: ReportView) => void;
}) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");

  const selectedLabel =
    value === "current-stock"
      ? "Current stock"
      : value === "recommended"
        ? "Recommended plans"
        : (scenarios.find((s) => s.id === value)?.name ?? "Scenario");

  const q = query.trim().toLowerCase();
  const matches = scenarios.filter((s) => s.name.toLowerCase().includes(q));

  function pick(v: ReportView) {
    onChange(v);
    setOpen(false);
    setQuery("");
  }

  const Row = ({
    active,
    disabled,
    name,
    sub,
    onSelect,
  }: {
    active: boolean;
    disabled?: boolean;
    name: string;
    sub: string;
    onSelect: () => void;
  }) => (
    <button
      type="button"
      role="option"
      aria-selected={active}
      disabled={disabled}
      onClick={onSelect}
      className={`flex w-full items-center gap-2 border-t border-gray-100 px-3.5 py-2.5 text-left first:border-t-0 disabled:cursor-not-allowed disabled:opacity-55 ${
        active ? "bg-brandlightblue" : "hover:bg-gray-50"
      }`}
    >
      <span className="min-w-0 flex-1">
        <span className="block truncate text-sm font-semibold text-brandblue">
          {name}
        </span>
        <span className="block truncate text-[0.7rem] text-gray-600">{sub}</span>
      </span>
      {disabled && (
        <span className="rounded bg-[#faf1e2] px-1.5 py-0.5 text-[0.62rem] font-bold text-[#9a5b10]">
          Awaiting modelling
        </span>
      )}
      {active && <Check className="h-4 w-4 text-midblue" />}
    </button>
  );

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <button
          type="button"
          aria-haspopup="listbox"
          aria-expanded={open}
          aria-label={`View: ${selectedLabel}. Change scenario`}
          className="inline-flex h-9 items-center gap-2.5 rounded-lg border border-gray-200 bg-white px-3 text-sm hover:border-gray-300"
        >
          <span className="text-[0.7rem] font-bold tracking-wide text-gray-600">
            VIEW
          </span>
          <span className="font-semibold text-brandblue">{selectedLabel}</span>
          <ChevronDown className="h-3.5 w-3.5 text-gray-600" />
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-80 p-0">
        <div className="flex items-center gap-2 border-b border-gray-100 px-3.5 py-2 text-gray-600">
          <Search className="h-3.5 w-3.5" />
          <input
            autoFocus
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search scenarios…"
            aria-label="Search scenarios"
            className="w-full bg-transparent text-sm text-brandblue outline-none placeholder:text-gray-600"
          />
        </div>
        <div role="listbox" aria-label="Scenarios" className="max-h-80 overflow-y-auto">
          <Row
            active={value === "current-stock"}
            name="Current stock"
            sub="No scenario applied"
            onSelect={() => pick("current-stock")}
          />
          <Row
            active={value === "recommended"}
            name="Recommended plans"
            sub="The engine's best plan per home"
            onSelect={() => pick("recommended")}
          />
          {matches.map((s) => (
            <Row
              key={s.id}
              active={value === s.id}
              disabled={s.status === "awaiting_modelling"}
              name={s.name}
              sub={scenarioGoalLine(s)}
              onSelect={() => pick(s.id)}
            />
          ))}
          {matches.length === 0 && q && (
            <p className="px-3.5 py-3 text-[0.78rem] text-gray-600">
              No scenarios match “{query}”.
            </p>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
