import { useEffect, useState } from "react";
import { useBackend } from "../../layouts";
import { AutomationRun } from "@onvo-ai/js";
import { Empty } from "../Empty";
import { ArrowPathIcon, BoltSlashIcon, CheckCircleIcon, EnvelopeIcon, ExclamationTriangleIcon } from "@heroicons/react/20/solid";
import React from "react";
import { Title, Text } from "../../tremor/Text";
import { Icon } from "../../tremor/Icon";
import { useAutomationsModal } from "./useAutomationsModal";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { Button } from "../../tremor/Button";
import { CalendarIcon, LinkIcon } from "@heroicons/react/24/outline";
import { toast } from "sonner";
import { Badge } from "../../tremor/Badge";
import { getSchedule, stringToArray } from "cron-converter";
import { Tooltip } from "../../tremor/Tooltip";

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

export const AutomationHistory: React.FC<{}> = ({ }) => {

    const { selectedAutomation } = useAutomationsModal();
    const { backend } = useBackend();
    const [loading, setLoading] = useState(false);
    const [automationRuns, setAutomationRuns] = useState<AutomationRun[]>([]);

    useEffect(() => {
        if (!selectedAutomation) return;
        getAutomationRuns(selectedAutomation.id);
    }, [selectedAutomation]);

    const getAutomationRuns = async (id: string) => {
        if (!backend || !id) return;
        const runs = await backend.automation(id).getRuns();
        setAutomationRuns(runs || []);
    }

    const testAutomation = () => {
        const id = selectedAutomation?.id;
        if (!backend || !id) return;
        if (!selectedAutomation) return;
        setLoading(true);

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

        toast.promise(async () => {
            await backend.automations.update(selectedAutomation.id, {
                ...selectedAutomation,
                next_run_at: next_run_at
            });
            return backend?.automation(id).test();
        }, {
            loading: "Running automation...",
            success: () => {
                setLoading(false);
                getAutomationRuns(id);
                return "Automation ran successfully!"
            },
            error: (err) => {
                setLoading(false);
                return "Failed to run automation: " + err.message;
            }
        })
    }

    return (<div className="onvo-foreground-color onvo-h-full onvo-flex onvo-flex-col !onvo-p-0 onvo-mb-8">
        <div className="onvo-px-4 onvo-background-color onvo-flex-shrink-0 onvo-py-2 onvo-border-solid onvo-border-b onvo-border-black/10 dark:onvo-border-white/10 onvo-flex onvo-flex-row onvo-items-center onvo-justify-center onvo-gap-3">
            <div className="onvo-max-w-screen-md onvo-mx-auto onvo-flex onvo-items-center onvo-justify-between onvo-flex-row onvo-w-full">
                <Icon variant="shadow" size="sm" icon={CalendarIcon} />
                <Title className="onvo-text-sm onvo-ml-2 onvo-flex-grow">Automation history</Title>
                <Button isLoading={loading} onClick={testAutomation}>Test automation</Button>
            </div>
        </div>
        <div className="onvo-overflow-y-auto">
            <div className="onvo-py-4 onvo-max-w-screen-md  onvo-mx-auto onvo-px-4">
                {(automationRuns.length === 0 && !loading) ? (
                    <Empty title="This automation has not been run yet." direction="column" subtitle="You will be able to see the status of each automation run once it has been executed at least once" icon={<BoltSlashIcon className="onvo-size-8" />} />
                ) : (<div className="onvo-flex onvo-flex-col onvo-gap-2 onvo-mt-2">
                    {loading && (<div
                        className="onvo-border-solid onvo-border onvo-flex onvo-flex-row onvo-items-center onvo-gap-2 onvo-px-2 onvo-py-2 onvo-shadow-sm onvo-rounded-2xl dark:onvo-border-slate-700"
                    ><ArrowPathIcon className="onvo-size-5 onvo-text-blue-500 onvo-animate-spin" />
                        <div className="onvo-flex-grow">
                            <Text className="onvo-text-xs onvo-flex-shrink-0">
                                Testing automation...
                            </Text>
                        </div>
                    </div>)}
                    {
                        automationRuns.map((a) => (
                            <div
                                key={a.id}
                                className="onvo-border-solid onvo-border onvo-flex onvo-flex-row onvo-items-center onvo-gap-2 onvo-px-2 onvo-py-2 onvo-shadow-sm onvo-rounded-2xl dark:onvo-border-slate-700"
                            >
                                {a.status === "success" ? (
                                    <CheckCircleIcon className="onvo-size-5 onvo-text-green-500" />
                                ) : (
                                    <ExclamationTriangleIcon className="onvo-size-5 onvo-text-red-500" />
                                )}

                                <div className="onvo-flex-grow">
                                    <Text className="onvo-text-xs onvo-flex-shrink-0">
                                        {a.status === "success" ? "Ran successfully " : "Run failed "}{`${dayjs(new Date(a.run_at)).fromNow()}`}
                                    </Text>
                                </div>

                                {a.status === "failure" && (
                                    <Tooltip content={a.error}><Badge variant="error" className="!onvo-rounded-full"><ExclamationTriangleIcon className="onvo-size-4 onvo-text-red-500" />Automation failed</Badge></Tooltip>
                                )}

                                {a.status === "success" && a.conditions_passed === false && (
                                    <Tooltip content={a.error}><Badge variant="warning" className="!onvo-rounded-full"><ExclamationTriangleIcon className="onvo-size-4 onvo-text-yellow-500" />Conditions failed</Badge></Tooltip>
                                )}
                                {a.status === "success" && a.conditions_passed === true && (
                                    <Badge variant="success" className="!onvo-rounded-full"><CheckCircleIcon className="onvo-size-4 onvo-text-green-500" />Conditions passed</Badge>
                                )}

                                {a.status === "success" && a.recipient_emails && a.recipient_emails.length >= 0 && (
                                    <Tooltip content={<ul>
                                        {(a.recipient_emails || []).map(email => (
                                            <li key={email}>{email}</li>
                                        ))}
                                    </ul>}>
                                        <Badge className="!onvo-rounded-full"><EnvelopeIcon className="onvo-size-4 onvo-text-blue-500" />{(a.recipient_emails || []).length} emails sent</Badge>
                                    </Tooltip>
                                )}

                                {a.status === "success" && a.webhook_sent === true && (
                                    <Badge className="!onvo-rounded-full"><LinkIcon className="onvo-size-4 onvo-text-blue-500" />Webhook sent</Badge>
                                )}
                            </div>
                        ))
                    }</div>)}
            </div>
        </div>
    </div>)
}