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

export default function ChatterboxListPrompt() {
    const [data, setData] = useState<string[]>([]);
    const [loading, setLoading] = useState(false);
    const [loadingDelete, setLoadingDelete] = useState<string | null>(null); // file yang sedang dihapus
    const [error, setError] = useState<string | null>(null);

    const [confirmOpen, setConfirmOpen] = useState(false);
    const [targetFile, setTargetFile] = useState<string | null>(null);

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

        try {
            const res = await apiFetch.api["chatterbox-tts"]["list-prompt"].get();
            setData(res.data?.data.prompt_names || []);
        } catch (err) {
            setError(err + "");
        } finally {
            setLoading(false);
        }
    };

    const removePrompt = async (filename: string) => {
        setLoadingDelete(filename);

        try {
            await apiFetch.api["chatterbox-tts"]["delete-prompt"].post({
                prompt_name: filename
            });

            // refresh list
            fetchList();
        } catch (err) {
            alert("Failed to remove: " + err);
        } finally {
            setLoadingDelete(null);
        }
    };

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

    const openRemoveDialog = (name: string) => {
        setTargetFile(name);
        setConfirmOpen(true);
    };

    return (
        <>
            {/* CONFIRM DELETE MODAL */}
            <Modal
                opened={confirmOpen}
                onClose={() => setConfirmOpen(false)}
                title="Confirm Remove"
                centered
            >
                <Stack>
                    <Text>Hapus file <b>{targetFile}</b> ?</Text>

                    <Group justify="flex-end">
                        <Button variant="default" onClick={() => setConfirmOpen(false)}>
                            Cancel
                        </Button>

                        <Button
                            color="red"
                            leftSection={<IconTrash size={16} />}
                            loading={loadingDelete === targetFile}
                            onClick={() => {
                                if (targetFile) removePrompt(targetFile);
                                setConfirmOpen(false);
                            }}
                        >
                            Remove
                        </Button>
                    </Group>
                </Stack>
            </Modal>

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

                        <Button
                            leftSection={!loading && <IconRefresh size={16} />}
                            onClick={fetchList}
                            loading={loading}
                            radius="md"
                        >
                            Refresh
                        </Button>
                    </Group>

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

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

                    {!loading && data.length === 0 && (
                        <Text ta="center" c="dimmed">
                            Belum ada prompt file yang terdaftar.
                        </Text>
                    )}

                    {!loading && data.length > 0 && (
                        <ScrollArea h={320}>
                            <Table highlightOnHover striped withTableBorder withColumnBorders>
                                <Table.Thead>
                                    <Table.Tr>
                                        <Table.Th>File Name</Table.Th>
                                        <Table.Th w={120}>Action</Table.Th>
                                    </Table.Tr>
                                </Table.Thead>

                                <Table.Tbody>
                                    {data.map((item, i) => (
                                        <Table.Tr key={i}>
                                            <Table.Td>{item}</Table.Td>

                                            <Table.Td>
                                                <Button
                                                    color="red"
                                                    size="xs"
                                                    radius="md"
                                                    leftSection={<IconTrash size={14} />}
                                                    loading={loadingDelete === item}
                                                    onClick={() => openRemoveDialog(item)}
                                                >
                                                    Remove
                                                </Button>
                                            </Table.Td>
                                        </Table.Tr>
                                    ))}
                                </Table.Tbody>
                            </Table>
                        </ScrollArea>
                    )}
                </Stack>
            </Card>
        </>
    );
}
