import { useEffect, useState } from "react";
import {
    Button,
    Card,
    Textarea,
    Select,
    Stack,
    Text,
    Loader,
    Alert,
    Group,
    Code,
    TextInput
} from "@mantine/core";
import { IconAlertTriangle, IconPlayerPlay } from "@tabler/icons-react";
import apiFetch from "@/lib/apiFetch";
import { useLocalStorage } from "@mantine/hooks";

export default function ChatterboxTTSAsync() {
    const [text, setText] = useState("");
    const [prompt, setPrompt] = useState<string | null>(null);
    const [title, setTitle] = useState("");

    const [promptList, setPromptList] = useState<string[]>([]);
    const [loadingPrompt, setLoadingPrompt] = useState(false);

    const [result, setResult] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    // Load available prompts
    const loadPrompts = async () => {
        setLoadingPrompt(true);
        try {
            const res = await apiFetch.api["chatterbox-tts"]["list-prompt"].get();
            setPromptList(res.data?.data?.prompt_names || []);
        } catch (err) {
            console.error(err);
        } finally {
            setLoadingPrompt(false);
        }
    };

    useEffect(() => {
        loadPrompts();
    }, []);

    const sendTTS = async () => {
        setLoading(true);
        setError(null);
        setResult(null);

        if (!text) {
            setError("Text is required");
            return;
        }

        if (!prompt) {
            setError("Prompt is required");
            return;
        }

        if (!title) {
            setError("Title is required");
            return;
        }

        try {
            const res = await apiFetch.api["chatterbox-tts"]["tts-async"].post({
                text,
                prompt: prompt || "",
                title: title || ""
            });

            setResult(res.data);

        } catch (err) {
            setError(err + "");
        } finally {
            setLoading(false);
        }
    };

    return (
        <Card shadow="md" radius="lg" p="xl" withBorder>
            <Stack gap="lg">

                {/* Title */}
                <Text fw={700} size="xl">
                    🔊 TTS Async Generator
                </Text>
                <TextInput 
                    label="Title"
                    placeholder="Masukkan judul"
                    value={title}
                    onChange={(e) => setTitle(e.currentTarget.value)}
                />

                {/* Input text */}
                <Textarea
                    label="Text to Convert"
                    placeholder="Masukkan teks untuk diubah menjadi audio..."
                    minRows={3}
                    autosize
                    value={text}
                    onChange={(e) => setText(e.currentTarget.value)}
                />

                {/* Select Prompt */}
                <Select
                    label="Voice Prompt"
                    placeholder={loadingPrompt ? "Loading prompts..." : "Select voice prompt"}
                    data={promptList}
                    value={prompt}
                    onChange={setPrompt}
                    searchable
                    disabled={loadingPrompt}
                    nothingFoundMessage="No prompt found"
                />

                {/* Generate Button */}
                <Button
                    onClick={sendTTS}
                    loading={loading}
                    disabled={!text || !prompt}
                    leftSection={<IconPlayerPlay size={16} />}
                    radius="md"
                >
                    Generate TTS
                </Button>

                {/* Error */}
                {error && (
                    <Alert
                        icon={<IconAlertTriangle />}
                        title="Error"
                        color="red"
                        radius="md"
                    >
                        {error}
                    </Alert>
                )}

                {/* Result */}
                {result && (
                    <Card shadow="sm" p="md" radius="md" bg="#fafafa" withBorder>
                        <Stack>
                            <Text fw={700}>Job Enqueued</Text>
                            <Text size="sm">
                                Job ID: <Code>{result?.job_id}</Code>
                            </Text>
                            <Text c="dimmed">
                                Use endpoint <Code>/result/{result?.job_id}</Code> to poll output.
                            </Text>
                        </Stack>
                    </Card>
                )}

            </Stack>
        </Card>
    );
}
