import { AutoComplete } from "antd";
import { useState } from "react";

export default function TamilInput() {
    const [value, setValue] = useState("");
    const [options, setOptions] = useState<any[]>([]);


    const searchTamil = async (text: string) => {
        setValue(text);

        if (!text) {
            setOptions([]);
            return;
        }

        try {
            const res = await fetch(
                `https://inputtools.google.com/request?itc=ta-t-i0-und&num=5&cp=0&cs=1&ie=utf-8&oe=utf-8&app=demopage&text=${encodeURIComponent(
                    text
                )}`
            );

            const data = await res.json();

            if (data && data[0] === "SUCCESS" && data[1]?.[0]?.[1]) {
                const words = data[1][0][1];

                setOptions(
                    words.map((word: string) => ({
                        value: word,
                    }))
                );
            }
        } catch {
            // Silently fallback if Google transliteration is unreachable
            setOptions([]);
        }
    };

    return (
        <AutoComplete
            style={{ width: 200 }}
            value={value}
            options={options}
            onSearch={searchTamil}
            onSelect={(v) => setValue(v)}
            placeholder="English to Tamil Typing..."
        />
    );
}