import { useEffect, useState } from "react";
import {
    Alert,
    Button,
    Card,
    Group,
    Loader,
    Modal,
    ScrollArea,
    Stack,
    Table,
    Text,
    ActionIcon,
    Code
} from "@mantine/core";
import {
    IconAlertTriangle,
    IconRefresh,
    IconDownload,
    IconTrash,
    IconPlayerPlay
} from "@tabler/icons-react";
import apiFetch from "@/lib/apiFetch";

export default function ChatterboxListFile() {
    const [files, setFiles] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [loadingDelete, setLoadingDelete] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);

    const [playModal, setPlayModal] = useState(false);
    const [currentUrl, setCurrentUrl] = useState<string | null>(null);
    const [loadingPlay, setLoadingPlay] = useState(false)

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

        try {
            const res = await apiFetch.api["chatterbox-tts"]["list-file"].get();
            setFiles(res.data?.data?.files || []);

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

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

    const removeFile = async (name: string) => {
        setLoadingDelete(name);
        try {
            await apiFetch.api["chatterbox-tts"]["rm"]({ filename: name }).delete();
            fetchFiles();
        } catch (err) {
            alert("Gagal menghapus: " + err);
        } finally {
            setLoadingDelete(null);
        }
    };

    const openPlay = async (filename: string) => {

        setLoadingPlay(true)
        try {
            const urlFetch = await apiFetch.api["chatterbox-tts"].file({ filename }).get()
            const res = await fetch(urlFetch.response.url);

            const blob = await res.blob();
            const url = URL.createObjectURL(blob);
            setCurrentUrl(url);
            setPlayModal(true);

            console.log("BLOB: ",blob)
            console.log("URL BLOB: ", url)

        } catch (error) {
            console.log("eh error")
        } finally {
            setLoadingPlay(false)
        }
    };

    return (
        <>
            {/* Modal Player */}
            <Modal
                opened={playModal}
                onClose={() => setPlayModal(false)}
                title="Audio Player"
                centered
                size="md"
            >
                {currentUrl && (
                    <audio controls style={{ width: "100%" }}>
                        <source src={currentUrl} type="audio/mpeg" />
                        Browser kamu tidak mendukung pemutar audio.
                    </audio>
                )}
            </Modal>

            {/* Main List Card */}
            <Card shadow="md" radius="lg" p="xl" withBorder>
                <Stack gap="lg">
                    <Group justify="space-between">
                        <Text size="xl" fw={700}>
                            🎧 Output Files
                        </Text>

                        <Button
                            leftSection={<IconRefresh size={16} />}
                            onClick={fetchFiles}
                            loading={loading}
                        >
                            Refresh
                        </Button>
                    </Group>

                    {error && (
                        <Alert
                            icon={<IconAlertTriangle />}
                            color="red"
                            radius="md"
                            title="Gagal memuat data"
                        >
                            {error}
                        </Alert>
                    )}

                    {loading && (
                        <Group justify="center" py="lg">
                            <Loader size="lg" />
                        </Group>
                    )}

                    {!loading && files.length === 0 && (
                        <Text ta="center" c="dimmed">
                            Belum ada file output.
                        </Text>
                    )}

                    {!loading && files.length > 0 && (
                        <ScrollArea h={350}>
                            <Table
                                striped
                                highlightOnHover
                                withTableBorder
                                withColumnBorders
                            >
                                <Table.Thead>
                                    <Table.Tr>
                                        <Table.Th>File Name</Table.Th>
                                        <Table.Th>Size</Table.Th>
                                        <Table.Th w={200}>Action</Table.Th>
                                    </Table.Tr>
                                </Table.Thead>

                                <Table.Tbody>
                                    {files.map((item, idx) => (
                                        <Table.Tr key={idx}>
                                            <Table.Td>
                                                <Code>{item.file}</Code>
                                            </Table.Td>

                                            <Table.Td>
                                                {(item.size_bytes / 1024).toFixed(1)} KB
                                            </Table.Td>

                                            <Table.Td>
                                                <Group justify="flex-end">

                                                    {/* Play */}
                                                    <ActionIcon
                                                        loading={loadingPlay}
                                                        variant="light"
                                                        color="blue"
                                                        size="lg"
                                                        radius="md"
                                                        onClick={() => openPlay(item.file)}
                                                    >
                                                        <IconPlayerPlay size={18} />
                                                    </ActionIcon>

                                                    {/* Download */}
                                                    <ActionIcon
                                                        variant="light"
                                                        color="green"
                                                        size="lg"
                                                        radius="md"
                                                        component="a"
                                                        href={`/tts-output/${item.file}`}
                                                        download={item.file}
                                                    >
                                                        <IconDownload size={18} />
                                                    </ActionIcon>

                                                    {/* Delete */}
                                                    <ActionIcon
                                                        variant="light"
                                                        color="red"
                                                        size="lg"
                                                        radius="md"
                                                        onClick={() => removeFile(item.file)}
                                                        loading={loadingDelete === item.file}
                                                    >
                                                        <IconTrash size={18} />
                                                    </ActionIcon>

                                                </Group>
                                            </Table.Td>
                                        </Table.Tr>
                                    ))}
                                </Table.Tbody>
                            </Table>
                        </ScrollArea>
                    )}
                </Stack>
            </Card>
        </>
    );
}
