"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import { RotateCcw, Search } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { loadLinkageGroupPageData } from "../api";
import { LinkageGroupEntityPage } from "./LinkageGroupEntityPage";
import { NONE_SELECT_VALUE, type LinkageGroupQuery, type SelectOption } from "../types";

const emptyQuery = (): LinkageGroupQuery => ({
  linkage_group_name: "",
  map_db_id: NONE_SELECT_VALUE,
});

function toSelectValue(value: string | null | undefined) {
  return value && value !== NONE_SELECT_VALUE ? value : NONE_SELECT_VALUE;
}

export function LinkageGroupTab() {
  const searchParams = useSearchParams();
  const [mapOptions, setMapOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<LinkageGroupQuery>(() => ({
    ...emptyQuery(),
    map_db_id: searchParams.get("map_db_id") ?? NONE_SELECT_VALUE,
  }));
  const [appliedQuery, setAppliedQuery] = useState<LinkageGroupQuery>(() => ({
    ...emptyQuery(),
    map_db_id: searchParams.get("map_db_id") ?? NONE_SELECT_VALUE,
  }));

  const urlDefaultFormValues = useMemo(() => {
    const mapDbId = searchParams.get("map_db_id");
    return mapDbId ? { map_db_id: mapDbId } : undefined;
  }, [searchParams]);

  useEffect(() => {
    let mounted = true;
    loadLinkageGroupPageData().then(({ options }) => {
      if (!mounted) return;
      setMapOptions(options.maps);
    });
    return () => { mounted = false; };
  }, []);

  const renderQueryForm = useCallback(() => (
    <div className="rounded-xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950">
      <div className="grid gap-3 md:grid-cols-2">
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">连锁群名称</Label>
          <Input
            value={draftQuery.linkage_group_name ?? ""}
            onChange={(event) => setDraftQuery((current) => ({
              ...current,
              linkage_group_name: event.target.value,
            }))}
            placeholder="名称模糊匹配"
          />
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">所属图谱</Label>
          <Select
            value={toSelectValue(draftQuery.map_db_id)}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, map_db_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部图谱" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部图谱</SelectItem>
              {mapOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="mt-3 flex justify-end gap-2">
        <Button type="button" variant="outline" className="gap-2" onClick={() => {
          const reset = emptyQuery();
          setDraftQuery(reset);
          setAppliedQuery(reset);
        }}>
          <RotateCcw className="h-4 w-4" />
          重置
        </Button>
        <Button type="button" className="gap-2" onClick={() => setAppliedQuery({ ...draftQuery })}>
          <Search className="h-4 w-4" />
          查询
        </Button>
      </div>
    </div>
  ), [draftQuery, mapOptions]);

  return (
    <LinkageGroupEntityPage
      mapOptions={mapOptions}
      linkageGroupQuery={appliedQuery}
      defaultFormValues={urlDefaultFormValues}
      renderQueryForm={renderQueryForm}
    />
  );
}
