import { __experimentalHStack as HStack, BaseControl, Button, Card, CardBody, CardHeader, SelectControl, ToggleControl, FormTokenField } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { useMutation, useQuery } from "@tanstack/react-query";
import { getPlooginsSettingsQueryOptions } from "@/shared/site-settings/query-options";
import { useForm } from "@tanstack/react-form";
import { updatePlooginsSettingsMutationOptions } from "@/shared/site-settings/mutation-options";
import { getPluginAuthorsQueryOptions, getSimpleSearchPluginsQueryOptions } from "@/shared/ploogins-search/query-options";
import { useState } from "@wordpress/element";

const Settings = () => {

    const { data: settings, isPending } = useQuery(getPlooginsSettingsQueryOptions())

    const { mutate: updateSettings, isPending: isUpdatingSettings } = useMutation(updatePlooginsSettingsMutationOptions())

    // State for author input value
    const [authorInputValue, setAuthorInputValue] = useState<string>('')
    const [excludeAuthorInputValue, setExcludeAuthorInputValue] = useState<string>('')

    const [pluginInputValue, setPluginInputValue] = useState<string>('')
    const [excludePluginInputValue, setExcludePluginInputValue] = useState<string>('')

    const { data: pluginsData } = useQuery(getSimpleSearchPluginsQueryOptions(pluginInputValue))
    const { data: excludePluginsData } = useQuery(getSimpleSearchPluginsQueryOptions(excludePluginInputValue))

    // Query for plugin authors based on input
    const { data: authorsData } = useQuery(getPluginAuthorsQueryOptions(authorInputValue))
    const { data: excludeAuthorsData } = useQuery(getPluginAuthorsQueryOptions(excludeAuthorInputValue))

    const pluginSuggestions = pluginsData?.data?.map(plugin => plugin.slug) || []
    const excludePluginSuggestions = excludePluginsData?.data?.map(plugin => plugin.slug) || []

    // Extract author names from the API response for suggestions
    const authorSuggestions = authorsData?.data?.map(author => author.author) || []
    const excludeAuthorSuggestions = excludeAuthorsData?.data?.map(author => author.author) || []

    const form = useForm({
        defaultValues: {
            max_results: settings?.max_results ?? 20,
            min_rating: settings?.min_rating ?? null,
            max_rating: settings?.max_rating ?? null,
            min_last_updated: settings?.min_last_updated ?? '',
            min_active_installs: settings?.min_active_installs ?? null,
            min_tested_version: settings?.min_tested_version ?? '',
            exclude_premium: settings?.exclude_premium ?? false,
            featured_authors: settings?.featured_authors ?? [],
            exclude_authors: settings?.exclude_authors ?? [],
            featured_plugins: settings?.featured_plugins ?? [],
            exclude_plugins: settings?.exclude_plugins ?? [],
        } as Settings,
        onSubmit: (values) => {
            updateSettings(values.value as Settings)
        }
    })

    return (
        <div className="h-full flex flex-col">

            <header style={{ padding: '16px 24px', borderBottom: '1px solid #f0f0f0' }} className="sticky top-0 bg-white flex justify-between items-center">
                <h2 className="!text-lg !font-medium !py-0 !my-0">{__('AI Search Settings', 'ploogins-ai-assistant')}</h2>

                <div>
                    <Button
                        variant="primary"
                        isBusy={isUpdatingSettings}
                        disabled={isUpdatingSettings || isPending}
                        onClick={() => form.handleSubmit()}
                    >
                        {__('Save', 'ploogins-ai-assistant')}
                    </Button>
                </div>
            </header>

            <div className="flex-1 overflow-y-scroll bg-neutral-50">
                <div className="p-6 space-y-6">
                    <Card className="max-w-screen-sm mx-auto">
                        <CardHeader>
                            <span className="!text-sm !font-medium !py-0 !my-0">{__('Search Results', 'ploogins-ai-assistant')}</span>
                        </CardHeader>

                        <CardBody>
                            <form.Field
                                name="max_results"
                                children={(field) => (
                                    <BaseControl
                                        id="max-results"
                                        label={__('Max results', 'ploogins-ai-assistant')}
                                        help={__('The maximum number of results to return.', 'ploogins-ai-assistant')}
                                    >
                                        <SelectControl
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value?.toString() as "10" | "20" | "30" | "50"}
                                            onBlur={field.handleBlur}
                                            onChange={(value) => field.handleChange(parseInt(value, 10))}
                                            options={[
                                                { label: "10", value: "10" },
                                                { label: "20", value: "20" },
                                                { label: "30", value: "30" },
                                                { label: "50", value: "50" },
                                            ]}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                            <HStack expanded={true}>
                                <form.Field
                                    name="min_rating"
                                    children={(field) => (
                                        <BaseControl
                                            className="w-full"
                                            id="min-rating"
                                            label={__('Minimum rating', 'ploogins-ai-assistant')}
                                            help={__('The minimum rating to return.', 'ploogins-ai-assistant')}
                                        >
                                            <SelectControl
                                                __next40pxDefaultSize
                                                __nextHasNoMarginBottom
                                                value={field.state.value?.toString() as "1" | "2" | "3" | "4" | "5" | ""}
                                                onBlur={field.handleBlur}
                                                onChange={(value) => field.handleChange(parseInt(value, 10))}
                                                options={[
                                                    { label: __('None', 'ploogins-ai-assistant'), value: "" },
                                                    { label: "⭐", value: "1" },
                                                    { label: "⭐⭐", value: "2" },
                                                    { label: "⭐⭐⭐", value: "3" },
                                                    { label: "⭐⭐⭐⭐", value: "4" },
                                                    { label: "⭐⭐⭐⭐⭐", value: "5" },
                                                ]}
                                            />
                                            {field.state.meta.errors.length > 0 && (
                                                <em>{field.state.meta.errors.join(',')}</em>
                                            )}
                                        </BaseControl>
                                    )}
                                />

                                <form.Field
                                    name="max_rating"
                                    children={(field) => (
                                        <BaseControl
                                            className="w-full"
                                            id="max-rating"
                                            label={__('Maximum rating', 'ploogins-ai-assistant')}
                                            help={__('The maximum rating to return.', 'ploogins-ai-assistant')}
                                        >
                                            <SelectControl
                                                __next40pxDefaultSize
                                                __nextHasNoMarginBottom
                                                value={field.state.value?.toString() as "1" | "2" | "3" | "4" | "5" | ""}
                                                onBlur={field.handleBlur}
                                                onChange={(value) => field.handleChange(parseInt(value, 10))}
                                                options={[
                                                    { label: __('None', 'ploogins-ai-assistant'), value: "" },
                                                    { label: "⭐", value: "1" },
                                                    { label: "⭐⭐", value: "2" },
                                                    { label: "⭐⭐⭐", value: "3" },
                                                    { label: "⭐⭐⭐⭐", value: "4" },
                                                    { label: "⭐⭐⭐⭐⭐", value: "5" },
                                                ]}
                                            />
                                            {field.state.meta.errors.length > 0 && (
                                                <em>{field.state.meta.errors.join(',')}</em>
                                            )}
                                        </BaseControl>
                                    )}
                                />
                            </HStack>

                            <form.Field
                                name="min_last_updated"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="min-last-updated"
                                        label={__('Minimum last updated', 'ploogins-ai-assistant')}
                                        help={__('The minimum last updated to return.', 'ploogins-ai-assistant')}
                                    >
                                        <SelectControl
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as "1 month ago" | "6 months ago" | "1 year ago" | ""}
                                            onBlur={field.handleBlur}
                                            onChange={(value) => field.handleChange(value)}
                                            options={[
                                                { label: __('None', 'ploogins-ai-assistant'), value: "" },
                                                { label: "1 month ago", value: "1 month ago" },
                                                { label: "6 months ago", value: "6 months ago" },
                                                { label: "1 year ago", value: "1 year ago" },
                                            ]}  
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                            <form.Field
                                name="min_active_installs"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="min-active-installs"
                                        label={__('Minimum active installs', 'ploogins-ai-assistant')}
                                        help={__('The minimum active installs to return.', 'ploogins-ai-assistant')}
                                    >
                                        <SelectControl
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value?.toString() as "100" | "1000" | "10000" | "100000" | "1000000" | ""}
                                            onBlur={field.handleBlur}
                                            onChange={(value) => field.handleChange(parseInt(value, 10))}
                                            options={[
                                                { label: __('None', 'ploogins-ai-assistant'), value: "" },
                                                { label: "100", value: "100" },
                                                { label: "1K", value: "1000" },
                                                { label: "10K", value: "10000" },
                                                { label: "100K", value: "100000" },
                                                { label: "1M", value: "1000000" },
                                            ]}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                            <form.Field
                                name="min_tested_version"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="min-tested-version"
                                        label={__('Minimum WordPress tested version', 'ploogins-ai-assistant')}
                                        help={__('The minimum WordPress tested version to return.', 'ploogins-ai-assistant')}
                                    >
                                        <SelectControl
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as "latest major" | "latest" | ""}
                                            onBlur={field.handleBlur}
                                            onChange={(value) => field.handleChange(value)}
                                            options={[
                                                { label: __('None', 'ploogins-ai-assistant'), value: "" },
                                                { label: "Latest Major Version", value: "latest major" },
                                                { label: "Latest Version", value: "latest" },
                                            ]}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                        </CardBody>
                    </Card>

                    <Card className="max-w-screen-sm mx-auto">
                        <CardHeader>
                            <span className="!text-sm !font-medium !py-0 !my-0">{__('Premium Plugins', 'ploogins-ai-assistant')}</span>
                        </CardHeader>

                        <CardBody>
                            <form.Field
                                name="exclude_premium"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="exclude-premium"
                                        label={__('Exclude premium plugins', 'ploogins-ai-assistant')}
                                    >
                                        <ToggleControl
                                            __nextHasNoMarginBottom
                                            checked={field.state.value}
                                            label={__('Exclude premium plugins from the search results.', 'ploogins-ai-assistant')}
                                            onChange={(value) => field.handleChange(value)}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />
                        </CardBody>
                    </Card>

                    <Card className="max-w-screen-sm mx-auto">
                        <CardHeader>
                            <span className="!text-sm !font-medium !py-0 !my-0">{__('Authors', 'ploogins-ai-assistant')}</span>
                        </CardHeader>

                        <CardBody>
                            <form.Field
                                name="featured_authors"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="featured-authors"
                                        label={__('Featured authors', 'ploogins-ai-assistant')}
                                    >
                                        <FormTokenField
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as string[]}
                                            onChange={(value) => field.handleChange(value.filter(item => typeof item === 'string') as string[])}
                                            label={''}
                                            onInputChange={(value) => {
                                                setAuthorInputValue(value)
                                            }}
                                            suggestions={authorSuggestions}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                            <form.Field
                                name="exclude_authors"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="exclude-authors"
                                        label={__('Exclude authors', 'ploogins-ai-assistant')}
                                    >
                                        <FormTokenField
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as string[]}
                                            onChange={(value) => field.handleChange(value.filter(item => typeof item === 'string') as string[])}
                                            label={''}
                                            onInputChange={(value) => {
                                                setExcludeAuthorInputValue(value)
                                            }}
                                            suggestions={excludeAuthorSuggestions}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />
                        </CardBody>
                    </Card>

                    <Card className="max-w-screen-sm mx-auto">
                        <CardHeader>
                            <span className="!text-sm !font-medium !py-0 !my-0">{__('Plugins', 'ploogins-ai-assistant')}</span>
                        </CardHeader>

                        <CardBody>
                            <form.Field
                                name="featured_plugins"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="featured-plugins"
                                        label={__('Featured plugins', 'ploogins-ai-assistant')}
                                    >
                                        <FormTokenField
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as string[]}
                                            onChange={(value) => field.handleChange(value.filter(item => typeof item === 'string') as string[])}
                                            label={''}
                                            onInputChange={(value) => {
                                                setPluginInputValue(value)
                                            }}
                                            suggestions={pluginSuggestions}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />

                            <form.Field
                                name="exclude_plugins"
                                children={(field) => (
                                    <BaseControl
                                        className="w-full"
                                        id="exclude-plugins"
                                        label={__('Exclude plugins', 'ploogins-ai-assistant')}
                                    >
                                        <FormTokenField
                                            __next40pxDefaultSize
                                            __nextHasNoMarginBottom
                                            value={field.state.value as string[]}
                                            onChange={(value) => field.handleChange(value.filter(item => typeof item === 'string') as string[])}
                                            label={''}
                                            onInputChange={(value) => {
                                                setExcludePluginInputValue(value)
                                            }}
                                            suggestions={excludePluginSuggestions}
                                        />
                                        {field.state.meta.errors.length > 0 && (
                                            <em>{field.state.meta.errors.join(',')}</em>
                                        )}
                                    </BaseControl>
                                )}
                            />
                        </CardBody>
                    </Card>
                </div>
            </div>

        </div>
    )
}

export default Settings;