"use client";

import { useState, useMemo, useRef } from "react";
import { SearchInput } from "@/components/ui/SearchInput";
import { ServiceTable, DEFAULT_COL_ORDER } from "@/components/admin/catalog/ServiceTable";
import type { ColumnKey } from "@/components/admin/catalog/ServiceTable";
import type { ServiceWithTags, CatalogFieldOptions } from "@/lib/admin-queries";

function loadColOrder(): ColumnKey[] {
  if (typeof window === "undefined") return DEFAULT_COL_ORDER;
  try {
    const saved = localStorage.getItem("catalog_col_order");
    if (saved) {
      const parsed = JSON.parse(saved) as ColumnKey[];
      // Validate: must contain exactly the same keys
      if (
        parsed.length === DEFAULT_COL_ORDER.length &&
        DEFAULT_COL_ORDER.every((k) => parsed.includes(k))
      ) {
        return parsed;
      }
    }
  } catch {}
  return DEFAULT_COL_ORDER;
}

function buildSortFn(
  sortKey: ColumnKey | null,
  sortDir: "asc" | "desc"
): (a: ServiceWithTags, b: ServiceWithTags) => number {
  if (!sortKey) return () => 0;
  const dir = sortDir === "asc" ? 1 : -1;
  return (a, b) => {
    switch (sortKey) {
      case "nome":
        return dir * a.name.localeCompare(b.name, "it");
      case "descrizione":
        return dir * (a.description ?? "").localeCompare(b.description ?? "", "it");
      case "fase":
        return dir * (a.fase ?? "").localeCompare(b.fase ?? "", "it");
      case "offerta":
        return dir * a.tags.join(",").localeCompare(b.tags.join(","), "it");
      case "pacchetto":
        return dir * a.pacchetto.join(",").localeCompare(b.pacchetto.join(","), "it");
      case "prezzo": {
        const na = parseFloat(a.unit_price ?? "0");
        const nb = parseFloat(b.unit_price ?? "0");
        return dir * (na - nb);
      }
      default:
        return 0;
    }
  };
}

export function CatalogSearch({
  services,
  options,
}: {
  services: ServiceWithTags[];
  options: CatalogFieldOptions;
}) {
  const [query, setQuery] = useState("");
  const [colOrder, setColOrder] = useState<ColumnKey[]>(() => loadColOrder());
  const [sortKey, setSortKey] = useState<ColumnKey | null>(null);
  const [sortDir, setSortDir] = useState<"asc" | "desc">("asc");
  const dragCol = useRef<ColumnKey | null>(null);

  function handleSortClick(key: ColumnKey) {
    if (sortKey === key) {
      setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    } else {
      setSortKey(key);
      setSortDir("asc");
    }
  }

  function handleColDragStart(key: ColumnKey) {
    dragCol.current = key;
  }

  function handleColDragOver(e: React.DragEvent, key: ColumnKey) {
    e.preventDefault();
  }

  function handleColDrop(targetKey: ColumnKey) {
    const from = dragCol.current;
    dragCol.current = null;
    if (!from || from === targetKey) return;
    setColOrder((prev) => {
      const next = [...prev];
      const fromIdx = next.indexOf(from);
      const toIdx = next.indexOf(targetKey);
      next.splice(fromIdx, 1);
      next.splice(toIdx, 0, from);
      try {
        localStorage.setItem("catalog_col_order", JSON.stringify(next));
      } catch {}
      return next;
    });
  }

  const sortFn = useMemo(() => buildSortFn(sortKey, sortDir), [sortKey, sortDir]);

  const { activeServices, inactiveServices } = useMemo(() => {
    const q = query.trim().toLowerCase();
    const filtered = q
      ? services.filter((s) => {
          if (s.name.toLowerCase().includes(q)) return true;
          if (s.category?.toLowerCase().includes(q)) return true;
          if (s.fase?.toLowerCase().includes(q)) return true;
          if (s.tags.some((t) => t.toLowerCase().includes(q))) return true;
          if (s.pacchetto.some((p) => p.toLowerCase().includes(q))) return true;
          return false;
        })
      : services;

    return {
      activeServices: [...filtered.filter((s) => s.active)].sort(sortFn),
      inactiveServices: [...filtered.filter((s) => !s.active)].sort(sortFn),
    };
  }, [services, query, sortFn]);

  return (
    <div className="space-y-4">
      <SearchInput
        placeholder="Cerca per nome, categoria, fase, tag o pacchetto..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        containerClassName="max-w-sm"
      />
      <ServiceTable
        activeServices={activeServices}
        inactiveServices={inactiveServices}
        options={options}
        colOrder={colOrder}
        sortKey={sortKey}
        sortDir={sortDir}
        onSortClick={handleSortClick}
        onColDragStart={handleColDragStart}
        onColDragOver={handleColDragOver}
        onColDrop={handleColDrop}
      />
    </div>
  );
}
