import { CodeBracketIcon, TrashIcon } from "@heroicons/react/24/outline";
import { useBackend } from "../../layouts";
import { useAutomationsModal } from "./useAutomationsModal";
import { Icon } from "../../tremor/Icon";
import { Card } from "../../tremor/Card";
import React, { useMemo, useState } from "react";
import { Title, Text } from "../../tremor/Text";
import { Button } from "../../tremor/Button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../tremor/Select";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import { Tabs, TabsList, TabsTrigger } from "../../tremor/Tabs";
import { Input } from "../../tremor/Input";
import { AutomationCondition } from "@onvo-ai/js";

const CONDITIONS = [{
    value: "lt",
    label: "Lesser than"
}, {
    value: "gt",
    label: "Greater than"
}, {
    value: "eq",
    label: "Equal to"
}, {
    value: "neq",
    label: "Not equal to"
}, {
    value: "lte",
    label: "Lesser than or equal to"
}, {
    value: "gte",
    label: "Greater than or equal to"
}];

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

    const { selectedAutomation, setSelectedAutomation } = useAutomationsModal();
    const { widgets } = useDashboard();

    const options = useMemo(() => {
        return widgets.filter(a => a && a.type === "metric").map(a => ({
            label: a.title,
            value: a.id
        }))
    }, [widgets]);

    const updateCondition = (index: number, condition: Partial<AutomationCondition>) => {
        const newConditions = (conditions.map((c, i) => {
            if (i === index) {
                return {
                    ...c,
                    ...condition
                }
            }
            return c;
        }));
        setSelectedAutomation({ conditions: newConditions });
    }

    const addCondition = () => {
        const newConditions = [...conditions, {
            operand_id: options[0].value,
            reference_type: "static" as const,
            operator: "lt",
            reference_value: "10"
        }]
        setSelectedAutomation({ conditions: newConditions });
    }

    const conditions = selectedAutomation?.conditions || [];


    return (<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-flex onvo-flex-row onvo-items-center onvo-justify-between onvo-rounded-t-2xl " + (conditions.length === 0 ? "onvo-rounded-b-2xl" : "")}>
            <div className="onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
                <Icon variant="shadow" size="xs" icon={CodeBracketIcon} />

                <Title className="onvo-text-sm">Condition</Title>
            </div>
            <Button variant="secondary" onClick={addCondition}>Add condition</Button>
        </div>
        {conditions.length > 0 && (
            <div className="onvo-p-4 onvo-flex onvo-flex-col onvo-gap-2 onvo-border-solid onvo-border-t onvo-border-black/10 dark:onvo-border-white/10">
                {conditions.map((condition, index) => (
                    <div key={index + "-condition"} className="onvo-flex onvo-flex-row onvo-items-center onvo-gap-2">
                        <Select value={condition.operand_id} onValueChange={(value) => updateCondition(index, { operand_id: value })}>
                            <SelectTrigger>
                                <SelectValue placeholder="Select" />
                            </SelectTrigger>
                            <SelectContent>
                                {options.map((item) => (
                                    <SelectItem key={item.value} value={item.value}>
                                        {item.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Select value={condition.operator} onValueChange={(value) => updateCondition(index, { operator: value })}>
                            <SelectTrigger>
                                <SelectValue placeholder="Select" />
                            </SelectTrigger>
                            <SelectContent>
                                {CONDITIONS.map((item) => (
                                    <SelectItem key={item.value} value={item.value}>
                                        {item.label}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <Tabs defaultValue="static" value={condition.reference_type} onValueChange={value => updateCondition(index, { reference_type: value as "static" | "dynamic" })}>
                            <TabsList variant="solid">
                                <TabsTrigger value="static">Static</TabsTrigger>
                                <TabsTrigger value="dynamic">Dynamic</TabsTrigger>
                            </TabsList>
                        </Tabs>
                        {
                            condition.reference_type === "static" ?
                                (<Input value={condition.reference_value} onChange={(e) => updateCondition(index, { reference_value: e.target.value })} />) :
                                (<Select value={condition.reference_id} onValueChange={(value) => updateCondition(index, { reference_id: value })}>
                                    <SelectTrigger>
                                        <SelectValue placeholder="Select" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {options.map((item) => (
                                            <SelectItem key={item.value} value={item.value}>
                                                {item.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>)
                        }

                        <Icon onClick={() => setSelectedAutomation({ conditions: conditions.filter((_, i) => i !== index) })} variant="shadow" className="!onvo-text-red-500 onvo-cursor-pointer" icon={TrashIcon} />

                    </div>))}
            </div>)}
        {conditions.length > 1 && (
            <div className="onvo-py-1 onvo-px-4 onvo-flex onvo-flex-row onvo-justify-between onvo-items-center onvo-border-solid onvo-border-t onvo-border-black/10 dark:onvo-border-white/10">
                <Tabs defaultValue="static" value={selectedAutomation?.condition_operator || "and"} onValueChange={value => setSelectedAutomation({ condition_operator: value })}>
                    <TabsList variant="solid">
                        <TabsTrigger value="and">AND</TabsTrigger>
                        <TabsTrigger value="or">OR</TabsTrigger>
                    </TabsList>
                </Tabs>
                {(selectedAutomation?.condition_operator || "and") === "and" ? (<Text>Report is only sent when all conditions are met</Text>) : (<Text>Report is sent when any condition is met</Text>)}

            </div>)}
    </Card>);
} 