"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 { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { loadMarkerPositionFilterOptions } from "../api";
import { MarkerPositionEntityPage } from "./MarkerPositionEntityPage";
import { NONE_SELECT_VALUE, type MarkerPositionQuery, type SelectOption } from "../types";

const emptyQuery = (): MarkerPositionQuery => ({
  map_db_id: NONE_SELECT_VALUE,
  linkage_group_name: NONE_SELECT_VALUE,
  variant_db_id: NONE_SELECT_VALUE,
});

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

export function MarkerPositionTab() {
  const searchParams = useSearchParams();
  const [mapOptions, setMapOptions] = useState<SelectOption[]>([]);
  const [linkageGroupOptions, setLinkageGroupOptions] = useState<SelectOption[]>([]);
  const [variantOptions, setVariantOptions] = useState<SelectOption[]>([]);
  const [draftQuery, setDraftQuery] = useState<MarkerPositionQuery>(() => ({
    ...emptyQuery(),
    map_db_id: searchParams.get("map_db_id") ?? NONE_SELECT_VALUE,
    linkage_group_name: searchParams.get("linkage_group_name") ?? NONE_SELECT_VALUE,
    variant_db_id: searchParams.get("variant_db_id") ?? NONE_SELECT_VALUE,
  }));
  const [appliedQuery, setAppliedQuery] = useState<MarkerPositionQuery>(() => ({
    ...emptyQuery(),
    map_db_id: searchParams.get("map_db_id") ?? NONE_SELECT_VALUE,
    linkage_group_name: searchParams.get("linkage_group_name") ?? NONE_SELECT_VALUE,
    variant_db_id: searchParams.get("variant_db_id") ?? NONE_SELECT_VALUE,
  }));

  useEffect(() => {
    let mounted = true;
    loadMarkerPositionFilterOptions()
      .then((options) => {
        if (!mounted) return;
        setMapOptions(options.maps);
        setLinkageGroupOptions(options.linkageGroups);
        setVariantOptions(options.variants);
      })
      .catch(() => {
        if (!mounted) return;
        setMapOptions([]);
        setLinkageGroupOptions([]);
        setVariantOptions([]);
      });
    return () => { mounted = false; };
  }, []);

  useEffect(() => {
    let mounted = true;
    const mapDbId = toSelectValue(draftQuery.map_db_id);
    loadMarkerPositionFilterOptions({
      mapDbId: mapDbId !== NONE_SELECT_VALUE ? mapDbId : undefined,
    }).then((options) => {
      if (!mounted) return;
      setLinkageGroupOptions(options.linkageGroups);
    });
    return () => { mounted = false; };
  }, [draftQuery.map_db_id]);

  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-3">
        <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,
              linkage_group_name: NONE_SELECT_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 className="space-y-1.5">
          <Label className="text-xs text-slate-500">连锁群</Label>
          <Select
            value={toSelectValue(draftQuery.linkage_group_name)}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, linkage_group_name: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部连锁群" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部连锁群</SelectItem>
              {linkageGroupOptions.map((option) => (
                <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
        <div className="space-y-1.5">
          <Label className="text-xs text-slate-500">Variant</Label>
          <Select
            value={toSelectValue(draftQuery.variant_db_id)}
            onValueChange={(value) => setDraftQuery((current) => ({ ...current, variant_db_id: value }))}
          >
            <SelectTrigger><SelectValue placeholder="全部 Variant" /></SelectTrigger>
            <SelectContent>
              <SelectItem value={NONE_SELECT_VALUE}>全部 Variant</SelectItem>
              {variantOptions.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, linkageGroupOptions, variantOptions]);

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

  return (
    <MarkerPositionEntityPage
      markerPositionQuery={appliedQuery}
      defaultFormValues={urlDefaultFormValues}
      renderQueryForm={renderQueryForm}
    />
  );
}
