import {useUpdatePath} from "../../utils/queries/path-queries";
import {useCreatePathSetting, usePathSetting} from "../../utils/queries/path-setting-queries";
import WebhookSettingPanel from "../Settings/PathSettings/WebhookSettingPanel";
import React, {useState} from "react";
import { Plus } from "lucide-react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "../ui/dialog";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "../ui/tabs";
import { Button } from "../ui/button";
import { Spinner } from "../ui/misc";

const PathSettingModal = ({ isOpen, path, onClose }) => {
    const settingId = path?.setting_id || 0;
    const {data: pathSetting, isLoading: isPathSettingLoading} = usePathSetting(settingId);
    const createPathSetting = useCreatePathSetting();
    const updatePath = useUpdatePath();

    const [activeTab, setActiveTab] = useState("webhook");
    const handleCreatePathSetting = () => {
        createPathSetting.mutate({}, {
            onSuccess: (res) => {
                updatePath.mutate({id: path.id, data: {setting_id: res.id}});
            }
        });
    };

    return (
        <Dialog open={isOpen} onOpenChange={(o) => { if (!o) onClose(); }}>
            <DialogContent className="max-w-3xl">
                <DialogHeader>
                    <DialogTitle>Path Settings</DialogTitle>
                </DialogHeader>
                {settingId && isPathSettingLoading ? (
                    <div className="flex justify-center py-10">
                        <Spinner label="Loading settings" />
                    </div>
                ) : !pathSetting ? (
                    <Button
                        type="button"
                        onClick={handleCreatePathSetting}
                    >
                        <Plus className="h-4 w-4" /> Create Path Setting
                    </Button>
                ) : (
                    <Tabs value={activeTab} onValueChange={setActiveTab}>
                        <TabsList>
                            <TabsTrigger value="webhook">Webhook</TabsTrigger>
                            <TabsTrigger value="template">Template</TabsTrigger>
                        </TabsList>
                        <TabsContent value="webhook">
                            <WebhookSettingPanel
                                pathSetting={pathSetting}
                                onClose={onClose}
                            />
                        </TabsContent>
                        <TabsContent value="template">
                            <div></div>
                        </TabsContent>
                    </Tabs>
                )}
            </DialogContent>
        </Dialog>
    );

};

export default PathSettingModal;
