"use client";

import { useState } from "react";
import { Zap, Play, Pause } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Label } from "@/components/ui/label";
import { toast } from "sonner";
import { apiFetch, type Automation } from "./types";

interface Props { automations: Automation[]; onCreated: () => void; }

export default function AutomationTab({ automations, onCreated }: Props) {
    const [automationName, setAutomationName] = useState("");
    const [automationType, setAutomationType] = useState("content_generation");

    const handleCreateAutomation = async () => {
        if (!automationName.trim()) { toast.error("Dale un nombre"); return; }
        try {
            const result = await apiFetch("/automation", {
                method: "POST",
                body: JSON.stringify({
                    name: automationName, type: automationType, trigger: "schedule",
                    triggerConfig: { schedule: "daily:09:00" },
                    actions: [{ type: "generate_content", prompt: "Genera contenido de lifestyle" }],
                }),
            });
            if (result.success) {
                toast.success("Automatización creada");
                setAutomationName("");
                onCreated();
            } else toast.error(result.error);
        } catch { toast.error("Error"); }
    };

    const handleToggleAutomation = async (id: string, currentStatus: boolean) => {
        try {
            await apiFetch("/automation", {
                method: "PUT",
                body: JSON.stringify({ id, isActive: !currentStatus }),
            });
            onCreated();
        } catch { toast.error("Error"); }
    };

    return (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card className="bg-slate-900/50 border-slate-800">
                <CardHeader><CardTitle className="flex items-center gap-2"><Zap className="h-5 w-5 text-amber-400" />Crear Automatización</CardTitle></CardHeader>
                <CardContent className="space-y-4">
                    <Input placeholder="Nombre de la automatización" value={automationName} onChange={(e) => setAutomationName(e.target.value)} className="bg-slate-800 border-slate-700" />
                    <div>
                        <Label className="text-xs text-slate-400">Tipo</Label>
                        <Select value={automationType} onValueChange={setAutomationType}>
                            <SelectTrigger className="bg-slate-800 border-slate-700 mt-1"><SelectValue /></SelectTrigger>
                            <SelectContent>
                                <SelectItem value="content_generation">Generación de Contenido</SelectItem>
                                <SelectItem value="posting">Publicación Automática</SelectItem>
                                <SelectItem value="cross_posting">Cross-Posting</SelectItem>
                                <SelectItem value="trend_tracking">Seguimiento de Tendencias</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                    <Button onClick={handleCreateAutomation} className="w-full bg-amber-600 hover:bg-amber-700">
                        <Zap className="h-4 w-4 mr-2" />Crear
                    </Button>
                </CardContent>
            </Card>

            <Card className="bg-slate-900/50 border-slate-800">
                <CardHeader><CardTitle>Automatizaciones Activas</CardTitle></CardHeader>
                <CardContent>
                    <ScrollArea className="h-64">
                        {automations.length === 0 ? (
                            <p className="text-slate-400 text-center py-8">No hay automatizaciones</p>
                        ) : (
                            <div className="space-y-2">
                                {automations.map((a) => (
                                    <div key={a.id} className="p-3 rounded-lg bg-slate-800/50 flex items-center justify-between">
                                        <div>
                                            <p className="font-medium text-sm">{a.name}</p>
                                            <p className="text-xs text-slate-400">{a.type} • {a.runCount} ejecuciones</p>
                                        </div>
                                        <Button size="sm" variant="ghost" onClick={() => handleToggleAutomation(a.id, a.isActive)}>
                                            {a.isActive ? <Pause className="h-4 w-4" /> : <Play className="h-4 w-4" />}
                                        </Button>
                                    </div>
                                ))}
                            </div>
                        )}
                    </ScrollArea>
                </CardContent>
            </Card>
        </div>
    );
}
