import React, { useState } from "react";
import { Icon } from "../../tremor/Icon";
import { Label, Text, Title } from "../../tremor/Text";
import { Card } from "../../tremor/Card";
import { Button } from "../../tremor/Button";
import { useBackend } from "../../layouts";
import { Automation } from "@onvo-ai/js";
import { SearchSelect } from "../../tremor/SearchSelect";
import { CronInput } from "../../tremor/CronInput";
import { Input } from "../../tremor/Input";
import { Timezones } from "./timezones";
import { Switch } from "../../tremor/Switch";
import { getSchedule, stringToArray } from "cron-converter";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { toast } from "sonner";

import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import { useAutomationsModal } from "./useAutomationsModal";
import { AutomationHistory } from "./AutomationHistory";
import { ClockIcon, PhotoIcon, TableCellsIcon, DocumentIcon, PresentationChartBarIcon, DocumentChartBarIcon, TrashIcon } from "@heroicons/react/24/outline";
import { AutomationConditionCard } from "./AutomationConditionCard";
import { AutomationEmailCard } from "./AutomationEmailCard";
import { AutomationWebhookCard } from "./AutomationWebhookCard";
import { Popover, PopoverTrigger, PopoverContent, PopoverClose } from "../../tremor/Popover";

dayjs.extend(relativeTime);
dayjs.extend(utc);
dayjs.extend(timezone);

export const AutomationEditor: React.FC<{}> = ({ }) => {
    const { selectedAutomation, setSelectedAutomation, getAllAutomations } = useAutomationsModal();
    const { backend } = useBackend();
    const [loading, setLoading] = useState(false);

    const updateAutomation = async () => {
        if (!backend) return;
        if (!selectedAutomation) return;

        const arr = stringToArray(selectedAutomation.schedule);
        let sch = getSchedule(arr, new Date(), selectedAutomation.timezone);
        let next_run_at = sch.next().toISO();

        toast.promise(() => {
            return backend.automations.update(selectedAutomation.id, {
                ...selectedAutomation,
                next_run_at: next_run_at
            })
        }, {
            loading: "Updating automation...",
            success: () => {
                return "Automation updated"
            },
            error: (e: any) => {
                return "Error updating automation: " + e.message
            }
        });
    }

    const updateSelectedAutomation = (update: Partial<Automation>) => {
        // @ts-ignore
        setSelectedAutomation({
            ...selectedAutomation, ...update
        });
    }

    const deleteAutomation = async () => {
        if (!backend || !selectedAutomation) return;
        setLoading(true);
        await backend.automations.delete(selectedAutomation.id);
        getAllAutomations(backend, selectedAutomation.dashboard);
        setSelectedAutomation(null);
    }


    return (<div className="onvo-flex-grow onvo-h-full onvo-flex onvo-flex-col">
        <div className="onvo-w-full onvo-border-solid onvo-border-b onvo-border-black/10 dark:onvo-border-white/10">
            <div className="onvo-max-w-screen-md onvo-mx-auto onvo-w-full onvo-p-2 onvo-flex onvo-flex-row onvo-items-center onvo-gap-2 ">
                <Text className="onvo-font-semibold onvo-mr-2">Title</Text>
                <Input
                    value={selectedAutomation?.title || ""}
                    onChange={(e) => updateSelectedAutomation({ title: e.target.value })}
                />
                <Popover>
                    <PopoverTrigger asChild>

                        <Icon icon={TrashIcon} variant="shadow" className="onvo-background-color onvo-p-1 onvo-text-red-500" />
                    </PopoverTrigger>
                    <PopoverContent className="p-4">
                        <Text>Are you sure you want to delete this automation?</Text>
                        <div className="onvo-flex onvo-flex-row onvo-gap-2 onvo-items-center onvo-mt-2">
                            <PopoverClose className="onvo-flex-grow onvo-w-full">
                                <Button className="onvo-flex-grow onvo-w-full">Cancel</Button>
                            </PopoverClose>
                            <Button className="onvo-flex-grow onvo-w-full" variant="destructive" onClick={deleteAutomation} isLoading={loading}>Delete</Button>
                        </div>

                    </PopoverContent>
                </Popover>

                <div className="onvo-flex onvo-items-center onvo-justify-between onvo-gap-3 onvo-rounded-md onvo-py-1.5 onvo-px-2 onvo-border-solid onvo-border dark:onvo-border-slate-700">
                    <Switch
                        size="small"
                        checked={selectedAutomation?.enabled}
                        onCheckedChange={(val) => updateSelectedAutomation({ enabled: val })}
                    />
                    <Label>Enabled</Label>
                </div>
                <Button onClick={updateAutomation}>Save</Button>
            </div></div>
        <PanelGroup autoSaveId="automation-editor" direction="vertical">
            <Panel defaultSize={85} minSize={10}>
                <div className="onvo-h-full onvo-background-color onvo-overflow-y-auto onvo-scrollbar-thin onvo-flex-grow dark:onvo-bg-dot-white/[0.2] onvo-p-8 onvo-bg-dot-black/[0.2] onvo-flex onvo-flex-col onvo-justify-start onvo-items-center">
                    <Card className="onvo-foreground-color onvo-max-w-screen-md !onvo-p-0">
                        <div className="onvo-background-color onvo-px-4 onvo-py-2 onvo-border-solid onvo-border-b onvo-rounded-t-2xl onvo-border-black/10 dark:onvo-border-white/10 onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
                            <Icon variant="shadow" size="xs" icon={ClockIcon} />

                            <Title className="onvo-text-sm">When</Title>
                        </div>
                        <div className="onvo-p-4">
                            <div className="onvo-flex onvo-flex-row onvo-items-center onvo-mt-2">
                                <CronInput
                                    value={selectedAutomation?.schedule || ""}
                                    onValueChange={(val) => updateSelectedAutomation({ schedule: val })}
                                />
                            </div>
                            <div className="onvo-flex onvo-flex-row onvo-items-center onvo-mt-2">
                                <Text className="onvo-w-24 onvo-flex-shrink-0 onvo-text-sm onvo-font-semibold">
                                    Timezone
                                </Text>
                                <div className="onvo-flex onvo-flex-grow onvo-flex-row onvo-justify-start">
                                    <SearchSelect
                                        value={selectedAutomation?.timezone}
                                        onValueChange={(val) => {
                                            updateSelectedAutomation({ timezone: val })
                                        }}
                                        items={Timezones}
                                    />
                                </div>
                            </div>
                        </div>
                    </Card>
                    <div className="onvo-z-10 onvo-relative onvo-h-8 onvo-w-full onvo-flex onvo-justify-center">
                        <div className="-onvo-top-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                        <div className="onvo-h-8 onvo-w-[2px] onvo-bg-slate-300 dark:onvo-bg-slate-800" />
                        <div className="-onvo-bottom-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                    </div>
                    <AutomationConditionCard />
                    <div className="onvo-z-10 onvo-relative onvo-h-8 onvo-w-full onvo-flex onvo-justify-center">
                        <div className="-onvo-top-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                        <div className="onvo-h-8 onvo-w-[2px] onvo-bg-slate-300 dark:onvo-bg-slate-800" />
                        <div className="-onvo-bottom-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                    </div>
                    <Card className="onvo-foreground-color onvo-max-w-screen-md !onvo-p-0">
                        <div className="onvo-background-color onvo-px-4 onvo-py-2 onvo-border-solid onvo-border-b onvo-rounded-t-2xl onvo-border-black/10 dark:onvo-border-white/10 onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
                            <Icon variant="shadow" size="xs" icon={DocumentChartBarIcon} />

                            <Title className="onvo-text-sm">Report format</Title>
                        </div>
                        <div className="onvo-p-4">

                            <div className="onvo-flex onvo-flex-row onvo-gap-4 onvo-w-full">
                                {[{
                                    title: "PDF", icon: DocumentIcon, id: "pdf"
                                }, {
                                    title: "Powerpoint", icon: PresentationChartBarIcon, id: "pptx"
                                }, {
                                    title: "Excel", icon: TableCellsIcon, id: "xlsx"
                                }, {
                                    title: "CSV", icon: TableCellsIcon, id: "csv"
                                }, {
                                    title: "Image", icon: PhotoIcon, id: "png"
                                }].map(format => (
                                    <Card key={format.id} onClick={() => {
                                        updateSelectedAutomation({ output_format: format.id })
                                    }} className={"onvo-cursor-pointer onvo-flex-grow !onvo-px-0 !onvo-py-2 onvo-flex onvo-flex-col onvo-justify-center onvo-items-center " + (selectedAutomation?.output_format === format.id ? "!onvo-border-blue-500 !onvo-shadow-blue-500 !onvo-text-blue-500" : "dark:onvo-text-slate-400")}>
                                        <format.icon className="onvo-size-8 onvo-mb-1" />
                                        <Text className="!onvo-text-inherit">{format.title}</Text>
                                    </Card>
                                ))}
                            </div>
                        </div>
                    </Card>
                    <div className="onvo-z-10 onvo-relative onvo-h-8 onvo-w-full onvo-flex onvo-justify-center">
                        <div className="-onvo-top-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                        <div className="onvo-h-8 onvo-w-[2px] onvo-bg-slate-300 dark:onvo-bg-slate-800" />
                        <div className="-onvo-bottom-1.5 onvo-absolute onvo-size-3 onvo-bg-slate-200 dark:onvo-bg-slate-700 onvo-left-[50%] -onvo-ml-1.5 onvo-rounded-full onvo-border-2 onvo-border-slate-300 dark:onvo-border-slate-800" />
                    </div>
                    {selectedAutomation?.method === "email" ? <AutomationEmailCard /> : <AutomationWebhookCard />}
                </div>
            </Panel>
            <PanelResizeHandle className="onvo-h-[1px] onvo-border-0 onvo-bg-black/10 dark:onvo-bg-white/10 hover:onvo-bg-black/50 dark:hover:onvo-bg-white/50 active:onvo-bg-black/50 dark:active:onvo-bg-white/50" />
            <Panel minSize={10}>
                <AutomationHistory />
            </Panel>
        </PanelGroup>

    </div>)
}