"use client";

import { Button } from "@workspace/ui/components/button";
import { Input } from "@workspace/ui/components/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@workspace/ui/components/select";
import { Combobox } from "@workspace/ui/composed/combobox";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

export function UserSearchBar({
  initialType,
  initialValue,
  onSearch,
  subscribes,
}: {
  initialType: string;
  initialValue: string;
  onSearch: (type: string, value: string) => void;
  subscribes?: API.SubscribeItem[];
}) {
  const { t } = useTranslation("user");
  const [searchType, setSearchType] = useState(initialType);
  const [searchValue, setSearchValue] = useState(initialValue);

  useEffect(() => {
    setSearchType(initialType);
    setSearchValue(initialValue);
  }, [initialType, initialValue]);

  return (
    <div className="flex items-center gap-2">
      <Select
        onValueChange={(v) => {
          setSearchType(v);
          setSearchValue("");
        }}
        value={searchType}
      >
        <SelectTrigger className="w-48">
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="email">设备码/邮箱</SelectItem>
          <SelectItem value="user_id">{t("userId", "User ID")}</SelectItem>
          <SelectItem value="subscribe_id">
            {t("subscription", "Subscription")}
          </SelectItem>
        </SelectContent>
      </Select>
      {searchType === "subscribe_id" ? (
        <Combobox
          className="w-48"
          onChange={(value) => {
            setSearchValue(value);
            onSearch("subscribe_id", value);
          }}
          options={subscribes?.map((item) => ({
            label: item.name!,
            value: String(item.id!),
          }))}
          placeholder={t("subscription", "Subscription")}
          value={searchValue}
        />
      ) : (
        <>
          <Input
            className="w-48"
            onChange={(e) => setSearchValue(e.target.value)}
            onKeyDown={(e) =>
              e.key === "Enter" && onSearch(searchType, searchValue)
            }
            placeholder={t("searchInputPlaceholder", "Enter search term")}
            value={searchValue}
          />
          <Button
            onClick={() => onSearch(searchType, searchValue)}
            variant="default"
          >
            {t("search", "Search")}
          </Button>
          {searchValue && (
            <Button
              onClick={() => {
                setSearchValue("");
                onSearch(searchType, "");
              }}
              variant="outline"
            >
              {t("resetSearch", "Reset")}
            </Button>
          )}
        </>
      )}
    </div>
  );
}
