"use client";

import * as React from "react";
import { Search, X } from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

import { searchDashboardWidgetIsinsClient } from "../../../_lib/dashboard-widgets-api";
import type { DashboardWidgetIsin } from "../../../_lib/dashboard-widgets-server-api";
import type { WidgetConfigPanelProps } from "../types";

export function IsinSelectionConfigPanel({
  tenant,
  widget,
  widgetSelections,
  onWidgetSelectionsChange,
}: WidgetConfigPanelProps) {
  if (!widget) {
    return <p className="text-muted-foreground text-sm">No widget selected.</p>;
  }

  const selectionKey = String(widget.widget_id);
  const value = widgetSelections[selectionKey] ?? [];

  return (
    <div className="space-y-3">
      <p className="text-muted-foreground text-sm leading-relaxed">
        Choose ISINs for this widget. Selections are applied when you save dashboard settings.
      </p>
      <IsinPicker
        tenant={tenant}
        value={value}
        onChange={(next) =>
          onWidgetSelectionsChange({
            ...widgetSelections,
            [selectionKey]: next,
          })
        }
      />
    </div>
  );
}

function IsinPicker({
  tenant,
  value,
  onChange,
}: {
  tenant: string;
  value: DashboardWidgetIsin[];
  onChange: (value: DashboardWidgetIsin[]) => void;
}) {
  const [query, setQuery] = React.useState("");
  const [results, setResults] = React.useState<DashboardWidgetIsin[]>([]);
  const [loading, setLoading] = React.useState(false);
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    if (!open) return;
    let cancelled = false;
    const timer = window.setTimeout(async () => {
      setLoading(true);
      try {
        const data = await searchDashboardWidgetIsinsClient(tenant, query);
        if (!cancelled) setResults(data.items);
      } catch {
        if (!cancelled) setResults([]);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }, 250);

    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [open, query, tenant]);

  const selectedIds = React.useMemo(() => new Set(value.map((item) => item.id)), [value]);
  const add = (item: DashboardWidgetIsin) => {
    if (!selectedIds.has(item.id)) onChange([...value, item]);
    setQuery("");
  };
  const uniqueResults = React.useMemo(() => {
    const seen = new Set<string>();
    return results.filter((item) => {
      if (!item.id || seen.has(item.id)) return false;
      seen.add(item.id);
      return true;
    });
  }, [results]);
  const uniqueValue = React.useMemo(() => {
    const seen = new Set<string>();
    return value.filter((item) => {
      if (!item.id || seen.has(item.id)) return false;
      seen.add(item.id);
      return true;
    });
  }, [value]);

  return (
    <div className="relative">
      <p className="mb-2 font-medium text-[11px] text-muted-foreground uppercase tracking-wide">
        ISIN selection
      </p>
      {uniqueValue.length > 0 ? (
        <div className="mb-2 flex flex-wrap gap-1.5">
          {uniqueValue.map((item) => (
            <Badge key={item.id} variant="secondary" className="max-w-full gap-1 pr-1">
              <span className="truncate">{item.text || item.id}</span>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="size-5 rounded-full"
                onClick={() => onChange(uniqueValue.filter((current) => current.id !== item.id))}
                aria-label={`Remove ${item.id}`}
              >
                <X className="size-3" />
              </Button>
            </Badge>
          ))}
        </div>
      ) : null}

      <div className="relative">
        <Search className="absolute top-2.5 left-2.5 size-4 text-muted-foreground" />
        <Input
          value={query}
          onChange={(event) => setQuery(event.target.value)}
          onFocus={() => setOpen(true)}
          onBlur={() => window.setTimeout(() => setOpen(false), 150)}
          placeholder="Search ISIN or asset name"
          className="pl-8"
        />
        {open ? (
          <div className="absolute z-20 mt-1 max-h-52 w-full overflow-y-auto rounded-md border bg-popover p-1 shadow-md">
            {loading ? <p className="px-3 py-2 text-muted-foreground text-xs">Searching…</p> : null}
            {!loading && uniqueResults.length === 0 ? (
              <p className="px-3 py-2 text-muted-foreground text-xs">No ISINs found.</p>
            ) : null}
            {!loading
              ? uniqueResults.map((item) => (
                  <button
                    key={item.id}
                    type="button"
                    disabled={selectedIds.has(item.id)}
                    className="block w-full rounded-sm px-3 py-2 text-left text-xs hover:bg-accent disabled:opacity-50"
                    onMouseDown={(event) => event.preventDefault()}
                    onClick={() => add(item)}
                  >
                    {item.text}
                  </button>
                ))
              : null}
          </div>
        ) : null}
      </div>
    </div>
  );
}
