import { router } from '@inertiajs/react';
import { Loader2, Plus, Search } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { search as featureSearch } from '@/routes/catalog/features';
import { features as trimFeatures } from '@/routes/catalog/trims';

interface SearchResult {
    code: string;
    name: string;
}

/*
 * PCM round 1 — "Add feature to trim" (BR Trims). A searchable panel over
 * the brand's feature structure (structure_elements type 'feature'), select
 * + availability, persisted as an entity_features row (Standard default).
 */
export function FeatureAddPanel({
    modelId,
    bodyTypeId,
    trimId,
    brandCode,
}: {
    modelId: number;
    bodyTypeId: number;
    trimId: number;
    brandCode: string;
}) {
    const [open, setOpen] = useState(false);
    const [query, setQuery] = useState('');
    const [results, setResults] = useState<SearchResult[]>([]);
    const [loading, setLoading] = useState(false);
    const [availability, setAvailability] = useState('Standard');

    useEffect(() => {
        const token = setTimeout(() => {
            const q = query.trim();

            if (q === '') {
                setResults([]);
                setLoading(false);

                return;
            }

            setLoading(true);

            const url = featureSearch({
                query: { brand: brandCode, q },
            }).url;

            fetch(url, { headers: { Accept: 'application/json' } })
                .then((response) => response.json())
                .then((data: { features: SearchResult[] }) =>
                    setResults(data.features),
                )
                .catch(() => setResults([]))
                .finally(() => setLoading(false));
        }, 250);

        return () => clearTimeout(token);
    }, [query, brandCode]);

    const attach = (code: string) => {
        router.post(
            trimFeatures({
                model: modelId,
                bodyType: bodyTypeId,
                trim: trimId,
            }) as never,
            { feature_code: code, availability },
            { preserveScroll: true, onSuccess: () => setOpen(false) },
        );
    };

    if (!open) {
        return (
            <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => setOpen(true)}
            >
                <Plus size={14} />
                Add feature
            </Button>
        );
    }

    return (
        <div className="rounded-xl border border-gray-100 bg-white p-3 shadow-sm">
            <div className="mb-2 flex items-center gap-2">
                <div className="relative flex-1">
                    <Input
                        autoFocus
                        value={query}
                        onChange={(event) => setQuery(event.target.value)}
                        placeholder="Search feature by code or name..."
                        className="bg-white py-1.5 pr-8 pl-8 text-xs"
                    />
                    <Search
                        size={12}
                        className="absolute top-2.5 left-2.5 text-gray-400"
                    />
                    {loading && (
                        <Loader2
                            size={12}
                            className="absolute top-2.5 right-2.5 animate-spin text-gray-400"
                        />
                    )}
                </div>
                <Select value={availability} onValueChange={setAvailability}>
                    <SelectTrigger
                        size="sm"
                        className="w-32 bg-white text-[11px]"
                    >
                        <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="Standard">Standard</SelectItem>
                        <SelectItem value="Optional">Optional</SelectItem>
                        <SelectItem value="NotAvailable">
                            Not available
                        </SelectItem>
                    </SelectContent>
                </Select>
            </div>

            <div className="max-h-56 overflow-y-auto">
                {results.length === 0 && !loading && (
                    <p className="px-1 py-3 text-[11px] text-gray-400">
                        {query.trim() === ''
                            ? 'Type at least one character to search the feature structure.'
                            : 'No matching features.'}
                    </p>
                )}
                {results.map((feature) => (
                    <button
                        key={feature.code}
                        type="button"
                        onClick={() => attach(feature.code)}
                        className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors hover:bg-slate-50"
                    >
                        <span className="font-mono text-[10px] text-astara-purple">
                            {feature.code}
                        </span>
                        <span className="truncate text-xs text-gray-600">
                            {feature.name}
                        </span>
                    </button>
                ))}
            </div>
        </div>
    );
}
