"use client";

import { useEffect, useState, useCallback } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Clock, Plus, MoreHorizontal, Trash2, Edit, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import { formatDistanceToNow } from "date-fns";

interface Task {
  id: string;
  name: string;
  description: string | null;
  cronExpression: string;
  command: string;
  isEnabled: boolean;
  lastRun: number | null;
  nextRun: number | null;
  createdAt: number;
}

const CRON_PRESETS = [
  { label: "Every minute", value: "* * * * *" },
  { label: "Every 5 minutes", value: "*/5 * * * *" },
  { label: "Every hour", value: "0 * * * *" },
  { label: "Every day at midnight", value: "0 0 * * *" },
  { label: "Every Sunday at 3am", value: "0 3 * * 0" },
];

function TaskForm({
  initial,
  onSubmit,
  onCancel,
  loading,
}: {
  initial?: Partial<Task>;
  onSubmit: (data: Omit<Task, "id" | "lastRun" | "nextRun" | "createdAt">) => void;
  onCancel: () => void;
  loading: boolean;
}) {
  const [name, setName] = useState(initial?.name ?? "");
  const [description, setDescription] = useState(initial?.description ?? "");
  const [cronExpression, setCronExpression] = useState(initial?.cronExpression ?? "0 0 * * *");
  const [command, setCommand] = useState(initial?.command ?? "");
  const [isEnabled, setIsEnabled] = useState(initial?.isEnabled ?? true);

  return (
    <div className="space-y-4">
      <div>
        <Label className="text-zinc-300">Task Name</Label>
        <Input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="e.g. Daily restart"
          className="mt-1 bg-zinc-800 border-zinc-700 text-white"
        />
      </div>
      <div>
        <Label className="text-zinc-300">Description (optional)</Label>
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Brief description"
          className="mt-1 bg-zinc-800 border-zinc-700 text-white"
        />
      </div>
      <div>
        <Label className="text-zinc-300">Cron Expression</Label>
        <Input
          value={cronExpression}
          onChange={(e) => setCronExpression(e.target.value)}
          placeholder="* * * * *"
          className="mt-1 bg-zinc-800 border-zinc-700 text-white font-mono"
        />
        <div className="flex flex-wrap gap-1 mt-2">
          {CRON_PRESETS.map((p) => (
            <button
              key={p.value}
              type="button"
              onClick={() => setCronExpression(p.value)}
              className="text-xs px-2 py-0.5 rounded bg-zinc-700 text-zinc-400 hover:bg-zinc-600 hover:text-white transition-colors"
            >
              {p.label}
            </button>
          ))}
        </div>
      </div>
      <div>
        <Label className="text-zinc-300">Minecraft Command</Label>
        <Input
          value={command}
          onChange={(e) => setCommand(e.target.value)}
          placeholder="e.g. say Server restart in 5 minutes"
          className="mt-1 bg-zinc-800 border-zinc-700 text-white font-mono"
        />
        <p className="text-xs text-zinc-500 mt-1">
          Enter a Minecraft command (without leading /) to execute via RCON.
        </p>
      </div>
      <div className="flex items-center gap-3">
        <Switch
          checked={isEnabled}
          onCheckedChange={setIsEnabled}
        />
        <Label className="text-zinc-300">Enable immediately</Label>
      </div>
      <DialogFooter>
        <Button variant="outline" onClick={onCancel} className="border-zinc-700 text-zinc-400">
          Cancel
        </Button>
        <Button
          onClick={() => onSubmit({ name, description: description || null, cronExpression, command, isEnabled })}
          disabled={!name || !cronExpression || !command || loading}
          className="bg-emerald-600 hover:bg-emerald-500 text-white"
        >
          {loading ? "Saving..." : "Save Task"}
        </Button>
      </DialogFooter>
    </div>
  );
}

export default function SchedulerPage() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editTask, setEditTask] = useState<Task | null>(null);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

  const fetchTasks = useCallback(async () => {
    try {
      const res = await fetch("/api/scheduler");
      if (res.ok) setTasks((await res.json()).tasks);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchTasks(); }, [fetchTasks]);

  const handleCreate = async (data: Parameters<typeof TaskForm>[0]["onSubmit"] extends (d: infer D) => void ? D : never) => {
    setSaving(true);
    try {
      const res = await fetch("/api/scheduler", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success("Task created");
      setDialogOpen(false);
      fetchTasks();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to create task");
    } finally {
      setSaving(false);
    }
  };

  const handleUpdate = async (data: Parameters<typeof TaskForm>[0]["onSubmit"] extends (d: infer D) => void ? D : never) => {
    if (!editTask) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/scheduler/${editTask.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success("Task updated");
      setEditTask(null);
      fetchTasks();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to update task");
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const res = await fetch(`/api/scheduler/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success("Task deleted");
      setTasks((p) => p.filter((t) => t.id !== id));
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to delete");
    }
    setDeleteId(null);
  };

  const toggleTask = async (task: Task) => {
    try {
      const res = await fetch(`/api/scheduler/${task.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isEnabled: !task.isEnabled }),
      });
      if (!res.ok) throw new Error((await res.json()).error);
      fetchTasks();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Failed to toggle");
    }
  };

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Scheduler</h1>
          <p className="text-zinc-400 text-sm mt-1">Automated recurring tasks</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={fetchTasks} className="border-zinc-700 text-zinc-400 hover:text-white">
            <RefreshCw className="w-4 h-4" />
          </Button>
          <Button size="sm" className="bg-emerald-600 hover:bg-emerald-500 text-white" onClick={() => setDialogOpen(true)}>
            <Plus className="w-4 h-4 mr-1.5" /> New Task
          </Button>
        </div>
      </div>

      <Card className="bg-zinc-900 border-zinc-800">
        <CardContent className="p-0">
          {loading ? (
            <div className="p-4 space-y-3">
              {[1,2,3].map(i => <Skeleton key={i} className="h-16 w-full bg-zinc-800" />)}
            </div>
          ) : tasks.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-zinc-600">
              <Clock className="w-10 h-10 mb-3 opacity-50" />
              <p>No scheduled tasks</p>
              <p className="text-sm mt-1">Create a task to automate server commands</p>
            </div>
          ) : (
            <div className="divide-y divide-zinc-800">
              {tasks.map(task => (
                <div key={task.id} className="flex items-center gap-4 px-4 py-4 hover:bg-zinc-800/50 transition-colors">
                  <Switch checked={task.isEnabled} onCheckedChange={() => toggleTask(task)} className="shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <p className="text-sm font-medium text-white">{task.name}</p>
                      {task.description && (
                        <span className="text-xs text-zinc-500">— {task.description}</span>
                      )}
                    </div>
                    <div className="flex items-center gap-3 flex-wrap">
                      <code className="text-xs text-emerald-400 bg-emerald-500/10 px-1.5 py-0.5 rounded">{task.cronExpression}</code>
                      <code className="text-xs text-zinc-400 font-mono">{task.command}</code>
                    </div>
                  </div>
                  <div className="text-right shrink-0">
                    {task.lastRun ? (
                      <p className="text-xs text-zinc-500">Last: {formatDistanceToNow(new Date(task.lastRun), { addSuffix: true })}</p>
                    ) : (
                      <p className="text-xs text-zinc-600">Never run</p>
                    )}
                  </div>
                  <DropdownMenu>
                    <DropdownMenuTrigger className="inline-flex shrink-0 items-center justify-center rounded-lg text-sm font-medium w-8 h-8 text-zinc-500 hover:text-white transition-all">
                      <MoreHorizontal className="w-4 h-4" />
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="bg-zinc-900 border-zinc-700">
                      <DropdownMenuItem onClick={() => setEditTask(task)} className="text-zinc-300 focus:text-white focus:bg-zinc-800">
                        <Edit className="w-4 h-4 mr-2" /> Edit
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => setDeleteId(task.id)} className="text-red-400 focus:text-red-300 focus:bg-zinc-800">
                        <Trash2 className="w-4 h-4 mr-2" /> Delete
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Create dialog */}
      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="bg-zinc-900 border-zinc-700">
          <DialogHeader>
            <DialogTitle className="text-white">New Scheduled Task</DialogTitle>
            <DialogDescription className="text-zinc-400">Schedule a Minecraft command to run automatically.</DialogDescription>
          </DialogHeader>
          <TaskForm onSubmit={handleCreate} onCancel={() => setDialogOpen(false)} loading={saving} />
        </DialogContent>
      </Dialog>

      {/* Edit dialog */}
      <Dialog open={!!editTask} onOpenChange={(o) => !o && setEditTask(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700">
          <DialogHeader>
            <DialogTitle className="text-white">Edit Task</DialogTitle>
          </DialogHeader>
          {editTask && <TaskForm initial={editTask} onSubmit={handleUpdate} onCancel={() => setEditTask(null)} loading={saving} />}
        </DialogContent>
      </Dialog>

      {/* Delete confirm */}
      <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent className="bg-zinc-900 border-zinc-700">
          <AlertDialogHeader>
            <AlertDialogTitle className="text-white">Delete task?</AlertDialogTitle>
            <AlertDialogDescription className="text-zinc-400">This will stop and remove the scheduled task permanently.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel className="border-zinc-700 text-zinc-400">Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={() => deleteId && handleDelete(deleteId)} className="bg-red-600 hover:bg-red-500 text-white">Delete</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
