"use client";

import React, { JSX, useState, useCallback, useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { Search, X, Loader2 } from "lucide-react";

import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Container } from "@/components/ui/container";
import Image from "next/image";
import { api } from "@/lib/api";
import type { ApiProduct } from "@/types/api";

// Security: Strict validation for search input
const formSchema = z.object({
    query: z.string()
        .min(1, "أدخل كلمة للبحث")
        .max(100, "كلمة البحث طويلة جداً")
        .regex(/^[\p{L}\p{N}\s\-_]+$/u, "استخدم حروف وأرقام فقط"),
});

type SearchFormValues = z.infer<typeof formSchema>;

interface SearchSuggestion {
    id: number;
    name: string;
    slug: string;
    image: string;
    price: string;
}

export default function SearchCTA(): JSX.Element {
    const router = useRouter();
    const [suggestions, setSuggestions] = useState<SearchSuggestion[]>([]);
    const [isSearching, setIsSearching] = useState(false);
    const [showSuggestions, setShowSuggestions] = useState(false);
    const [debounceTimer, setDebounceTimer] = useState<NodeJS.Timeout | null>(null);

    const form = useForm<SearchFormValues>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            query: "",
        },
    });

    const watchQuery = form.watch("query");

    // Security: Sanitize search input to prevent XSS
    const sanitizeSearchQuery = (query: string): string => {
        return query
            .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '') // Remove script tags
            .replace(/<[^>]*>/g, '') // Remove HTML tags
            .replace(/[^\p{L}\p{N}\s\-_]/gu, '') // Only allow letters, numbers, spaces, hyphens, underscores
            .trim()
            .substring(0, 100); // Limit length
    };

    // Debounced search for suggestions (performance optimization)
    const fetchSuggestions = useCallback(async (query: string) => {
        if (query.length < 2) {
            setSuggestions([]);
            setShowSuggestions(false);
            return;
        }

        // Sanitize before sending to API
        const sanitizedQuery = sanitizeSearchQuery(query);
        
        if (sanitizedQuery.length === 0) {
            setSuggestions([]);
            setShowSuggestions(false);
            return;
        }

        try {
            setIsSearching(true);
            
            // API call with sanitized query
            const response = await api.get<{
                data: ApiProduct[];
            }>(`/products?search=${encodeURIComponent(sanitizedQuery)}&page=1`);

            // Map and limit results to top 5
            const productSuggestions: SearchSuggestion[] = response.data.slice(0, 5).map((product: ApiProduct) => ({
                id: product.id,
                name: product.name,
                slug: product.slug,
                image: product.images?.[0] || '/assets/placeholder.png',
                price: String(product.variants?.[0]?.price || product.base_price || '0'),
            }));

            setSuggestions(productSuggestions);
            setShowSuggestions(true);
        } catch (error) {
            console.error('Search error:', error);
            setSuggestions([]);
        } finally {
            setIsSearching(false);
        }
    }, []);

    // Debounce search input (wait 300ms after user stops typing)
    useEffect(() => {
        if (debounceTimer) {
            clearTimeout(debounceTimer);
        }

        if (watchQuery && watchQuery.length >= 2) {
            const timer = setTimeout(() => {
                fetchSuggestions(watchQuery);
            }, 300); // 300ms debounce delay

            setDebounceTimer(timer);
        } else {
            setSuggestions([]);
            setShowSuggestions(false);
        }

        return () => {
            if (debounceTimer) {
                clearTimeout(debounceTimer);
            }
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [watchQuery]);

    const onSubmit = (data: SearchFormValues) => {
        const sanitizedQuery = sanitizeSearchQuery(data.query);
        
        if (sanitizedQuery.length === 0) {
            form.setError("query", { message: "استخدم حروف وأرقام فقط" });
            return;
        }

        // Navigate to products page with search query
        router.push(`/products?search=${encodeURIComponent(sanitizedQuery)}`);
        setShowSuggestions(false);
    };

    const handleSuggestionClick = (slug: string) => {
        router.push(`/products/${slug}`);
        setShowSuggestions(false);
        form.reset();
    };

    const clearSearch = () => {
        form.reset();
        setSuggestions([]);
        setShowSuggestions(false);
    };

    return (
        <section className="w-full px-4 lg:px-6">
            <Container>
                <div className="relative mx-auto w-full rounded-[20px] bg-[#212736]">
                    <svg
                        className="absolute left-1/2 -top-10 -translate-x-1/2 w-[187px] h-[41px]"
                        viewBox="0 0 187 41"
                        xmlns="http://www.w3.org/2000/svg"
                    >
                        <path
                            d="M0 41 L93.5 0 Q93.5 0 94 0 L187 41 Z"
                            fill="#212736"
                        />
                    </svg>

                    <Image src='/assets/icons/star.svg' alt="star" width={27} height={27} className="absolute bottom-40 sm:bottom-[190px] md:bottom-[260px] lg:bottom-[71px] left-12 sm:left-[250px] lg:left-[486px]" />

                    <div className="flex items-start justify-between lg:flex-row flex-col gap-11 lg:gap-6 pt-8 sm:pt-[50px] pb-6 md:pb-[77px] lg:pr-[50px] px-5 sm:px-10 lg:pl-[73px] relative z-10">
                        <h2 className="max-w-[350px] mx-auto lg:mx-0 lg:max-w-[472px] text-white prompt text-[28px] sm:text-[36px] lg:text-[46px] leading-[34px] sm:leading-[42px] lg:leading-[55px] font-bold tracking-[-0.9px] text-center md:text-left">
                            ابحث عن منتجاتك المفضلة
                        </h2>

                        <Card className="w-full lg:min-w-[350px] lg:max-w-[591px] rounded-lg sm:rounded-[20px] bg-[#EFF0F1] border-0 mt-2 sm:mt-[25px] relative">
                            <CardContent className="px-3 sm:px-[23px] pb-[11px] pt-5 sm:pt-8">
                                <Form {...form}>
                                    <form
                                        onSubmit={form.handleSubmit(onSubmit)}
                                        className="space-y-4 sm:space-y-[23px]"
                                    >
                                        <FormField
                                            control={form.control}
                                            name="query"
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormLabel className="sr-only">بحث</FormLabel>
                                                    <FormControl>
                                                        <div className="relative">
                                                            <div className="flex items-center gap-3 sm:gap-[21px]">
                                                                <Search className="w-6 sm:w-[30px] h-6 sm:h-[30px] text-[#01081A]" />
                                                                <Input
                                                                    placeholder="ابحث عن المنتجات..."
                                                                    {...field}
                                                                    autoComplete="off"
                                                                    maxLength={100}
                                                                    className="h-auto outline-none border-none bg-transparent w-full text-[18px] sm:text-[21px] font-light leading-[22px] sm:leading-[26px] text-[#01081A] placeholder:text-[#01081A]/60 pr-8"
                                                                />
                                                                {field.value && (
                                                                    <button
                                                                        type="button"
                                                                        onClick={clearSearch}
                                                                        className="absolute left-2 p-1 hover:bg-gray-200 rounded-full transition-colors"
                                                                        aria-label="Clear search"
                                                                    >
                                                                        <X className="w-5 h-5 text-gray-500" />
                                                                    </button>
                                                                )}
                                                                {isSearching && (
                                                                    <Loader2 className="absolute left-2 w-5 h-5 text-[#F5411C] animate-spin" />
                                                                )}
                                                            </div>
                                                            
                                                            {/* Search Suggestions Dropdown */}
                                                            {showSuggestions && suggestions.length > 0 && (
                                                                <div className="absolute top-full left-0 right-0 mt-2 bg-white rounded-lg shadow-lg border border-gray-200 max-h-[300px] overflow-y-auto z-50">
                                                                    {suggestions.map((suggestion) => (
                                                                        <button
                                                                            key={suggestion.id}
                                                                            type="button"
                                                                            onClick={() => handleSuggestionClick(suggestion.slug)}
                                                                            className="w-full flex items-center gap-3 p-3 hover:bg-gray-50 transition-colors text-right border-b last:border-b-0"
                                                                        >
                                                                            <Image
                                                                                src={suggestion.image}
                                                                                alt={suggestion.name}
                                                                                width={50}
                                                                                height={50}
                                                                                className="w-12 h-12 object-cover rounded"
                                                                                unoptimized={suggestion.image.startsWith('data:image')}
                                                                            />
                                                                            <div className="flex-1 text-right">
                                                                                <p className="text-sm font-medium text-gray-900 line-clamp-1">
                                                                                    {suggestion.name}
                                                                                </p>
                                                                                <p className="text-sm text-[#F5411C] font-semibold">
                                                                                    {suggestion.price} د.ع
                                                                                </p>
                                                                            </div>
                                                                        </button>
                                                                    ))}
                                                                </div>
                                                            )}
                                                        </div>
                                                    </FormControl>
                                                    <FormMessage className="text-[#F5411C]" />
                                                </FormItem>
                                            )}
                                        />

                                        <Button
                                            type="submit"
                                            disabled={isSearching}
                                            className="w-full rounded-lg sm:rounded-[14px] text-[17px] leading-[21px] font-medium py-[13px] bg-[#F5411C] text-white hover:bg-[#e44527] disabled:opacity-50"
                                        >
                                            {isSearching ? (
                                                <>
                                                    <Loader2 className="w-4 h-4 animate-spin ml-2" />
                                                    جارٍ البحث...
                                                </>
                                            ) : (
                                                'بحث'
                                            )}
                                        </Button>
                                    </form>
                                </Form>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </Container>
        </section>
    );
}
