import { SaveButton } from "@/components/Common/SaveButton"
import { getSearchSettings, setSearchSettings } from "@/services/search"
import { ALL_GOOGLE_DOMAINS } from "@/utils/google-domains"
import { SUPPORTED_SEARCH_PROVIDERS } from "@/utils/search-provider"
import { useForm } from "@mantine/form"
import { useQuery } from "@tanstack/react-query"
import { Select, Skeleton, Switch, InputNumber, Input } from "antd"
import { useTranslation } from "react-i18next"

export const SearchModeSettings = () => {
  const { t } = useTranslation("settings")

  const form = useForm({
    initialValues: {
      isSimpleInternetSearch: false,
      searchProvider: "",
      totalSearchResults: 0,
      visitSpecificWebsite: false,
      searxngURL: "",
      searxngJSONMode: false,
      braveApiKey: "",
      tavilyApiKey: "",
      googleDomain: "",
      defaultInternetSearchOn: false,
      exaAPIKey: "",
      firecrawlAPIKey: "",
      ollamaSearchApiKey: "",
      kagiApiKey: "",
      perplexityApiKey: "",
      domainFilterList: [] as string[],
      blockedDomainList: [] as string[]
    }
  })

  const { status } = useQuery({
    queryKey: ["fetchSearchSettings"],
    queryFn: async () => {
      const data = await getSearchSettings()
      form.setValues(data)
      return data
    }
  })

  if (status === "pending" || status === "error") {
    return <Skeleton active />
  }

  return (
    <div>
      <div className="mb-5">
        <h2 className="text-base font-semibold leading-7 text-gray-900 dark:text-white">
          {t("generalSettings.webSearch.heading")}
        </h2>
        <div className="border border-b border-gray-200 dark:border-gray-600 mt-3"></div>
      </div>
      <form
        onSubmit={form.onSubmit(async (values) => {
          await setSearchSettings(values)
        })}
        className="space-y-4">
        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <span className="text-gray-700 dark:text-neutral-50 ">
            {t("generalSettings.webSearch.provider.label")}
          </span>
          <div>
            <Select
              placeholder={t("generalSettings.webSearch.provider.placeholder")}
              showSearch
              className="w-full mt-4 sm:mt-0 sm:w-[200px]"
              options={SUPPORTED_SEARCH_PROVIDERS}
              filterOption={(input, option) =>
                option!.label.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
                option!.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              {...form.getInputProps("searchProvider")}
            />
          </div>
        </div>
        {form.values.searchProvider === "searxng" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.searxng.url.label")}
              </span>
              <div>
                <Input
                  placeholder="https://searxng.example.com"
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  required
                  {...form.getInputProps("searxngURL")}
                />
              </div>
            </div>
          </>
        )}
        {form.values.searchProvider === "google" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.googleDomain.label")}
              </span>
              <div>
                <Select
                  showSearch
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  options={ALL_GOOGLE_DOMAINS.map((e) => ({
                    label: e,
                    value: e
                  }))}
                  filterOption={(input, option) =>
                    option!.label.toLowerCase().indexOf(input.toLowerCase()) >=
                      0 ||
                    option!.value.toLowerCase().indexOf(input.toLowerCase()) >=
                      0
                  }
                  {...form.getInputProps("googleDomain")}
                />
              </div>
            </div>
          </>
        )}
        {form.values.searchProvider === "brave-api" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.braveApi.label")}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.braveApi.placeholder"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("braveApiKey")}
                />
              </div>
            </div>
          </>
        )}
        {form.values.searchProvider === "tavily-api" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.tavilyApi.label")}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.tavilyApi.placeholder"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("tavilyApiKey")}
                />
              </div>
            </div>
          </>
        )}

        {form.values.searchProvider === "exa" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.exa.label")}
              </span>
              <div>
                <Input.Password
                  placeholder={t("generalSettings.webSearch.exa.placeholder")}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("exaAPIKey")}
                />
              </div>
            </div>
          </>
        )}

        {form.values.searchProvider === "firecrawl" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t("generalSettings.webSearch.firecrawlAPIKey.label")}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.firecrawlAPIKey.placeholder"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("firecrawlAPIKey")}
                />
              </div>
            </div>
          </>
        )}

        {form.values.searchProvider === "ollama-search" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t(
                  "generalSettings.webSearch.ollamaSearchApiKey.label",
                  "Ollama Search API Key"
                )}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.ollamaSearchApiKey.placeholder",
                    "Ollama Search API Key"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("ollamaSearchApiKey")}
                />
              </div>
            </div>
          </>
        )}

        {form.values.searchProvider === "kagi-api" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t(
                  "generalSettings.webSearch.kagiApi.label",
                  "Kagi API Key"
                )}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.kagiApi.placeholder",
                    "Kagi API Key"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("kagiApiKey")}
                />
              </div>
            </div>
          </>
        )}

        {form.values.searchProvider === "perplexity-api" && (
          <>
            <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
              <span className="text-gray-700 dark:text-neutral-50">
                {t(
                  "generalSettings.webSearch.perplexityApi.label",
                  "Perplexity API Key"
                )}
              </span>
              <div>
                <Input.Password
                  placeholder={t(
                    "generalSettings.webSearch.perplexityApi.placeholder",
                    "Perplexity API Key"
                  )}
                  required
                  className="w-full mt-4 sm:mt-0 sm:w-[200px]"
                  {...form.getInputProps("perplexityApiKey")}
                />
              </div>
            </div>
          </>
        )}

        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <span className="text-gray-700 dark:text-neutral-50 ">
            {t("generalSettings.webSearch.searchMode.label")}
          </span>
          <div>
            <Switch
              className="mt-4 sm:mt-0"
              {...form.getInputProps("isSimpleInternetSearch", {
                type: "checkbox"
              })}
            />
          </div>
        </div>
        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <span className="text-gray-700 dark:text-neutral-50 ">
            {t("generalSettings.webSearch.totalSearchResults.label")}
          </span>
          <div>
            <InputNumber
              placeholder={t(
                "generalSettings.webSearch.totalSearchResults.placeholder"
              )}
              {...form.getInputProps("totalSearchResults")}
              className="!w-full mt-4 sm:mt-0 sm:w-[200px]"
            />
          </div>
        </div>

        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <span className="text-gray-700 dark:text-neutral-50 ">
            {t("generalSettings.webSearch.visitSpecificWebsite.label")}
          </span>
          <div>
            <Switch
              className="mt-4 sm:mt-0"
              {...form.getInputProps("visitSpecificWebsite", {
                type: "checkbox"
              })}
            />
          </div>
        </div>

        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <span className="text-gray-700 dark:text-neutral-50 ">
            {t("generalSettings.webSearch.searchOnByDefault.label")}
          </span>
          <div>
            <Switch
              className="mt-4 sm:mt-0"
              {...form.getInputProps("defaultInternetSearchOn", {
                type: "checkbox"
              })}
            />
          </div>
        </div>

        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <div className="flex flex-col space-y-1">
            <span className="text-gray-700 dark:text-neutral-50">
              {t("generalSettings.webSearch.domainFilter.label", "Domain Filter List")}
            </span>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t("generalSettings.webSearch.domainFilter.description", "Only show results from these domains")}
            </p>
          </div>
          <div className="w-full mt-4 sm:mt-0 sm:w-[200px]">
            <Select
              mode="tags"
              placeholder={t("generalSettings.webSearch.domainFilter.placeholder", "e.g., example.com")}
              className="w-full"
              tokenSeparators={[',', ' ']}
              {...form.getInputProps("domainFilterList")}
            />
          </div>
        </div>

        <div className="flex sm:flex-row flex-col space-y-4 sm:space-y-0 sm:justify-between">
          <div className="flex flex-col space-y-1">
            <span className="text-gray-700 dark:text-neutral-50">
              {t("generalSettings.webSearch.blockedDomains.label", "Blocked Domains")}
            </span>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {t("generalSettings.webSearch.blockedDomains.description", "Exclude results from these domains")}
            </p>
          </div>
          <div className="w-full mt-4 sm:mt-0 sm:w-[200px]">
            <Select
              mode="tags"
              placeholder={t("generalSettings.webSearch.blockedDomains.placeholder", "e.g., spam.com")}
              className="w-full"
              tokenSeparators={[',', ' ']}
              {...form.getInputProps("blockedDomainList")}
            />
          </div>
        </div>

        <div className="flex justify-end">
          <SaveButton btnType="submit" />
        </div>
      </form>
    </div>
  )
}
