"use client";

import { useEffect, useState, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button, buttonVariants } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Puzzle,
  Search,
  RefreshCw,
  MoreHorizontal,
  Power,
  RotateCcw,
  Upload,
} from "lucide-react";
import { toast } from "sonner";

interface Plugin {
  id: string;
  name: string;
  version: string | null;
  description: string | null;
  isEnabled: boolean;
  jarFile: string | null;
  installedAt: number;
}

export default function PluginsPage() {
  const [plugins, setPlugins] = useState<Plugin[]>([]);
  const [jarFiles, setJarFiles] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchPlugins = useCallback(async () => {
    try {
      const res = await fetch("/api/plugins");
      if (res.ok) {
        const data = await res.json();
        setPlugins(data.plugins);
        setJarFiles(data.jarFiles);
      }
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleAction = async (
    name: string,
    action: "enable" | "disable" | "reload",
  ) => {
    setActionLoading(`${name}-${action}`);
    try {
      const res = await fetch(`/api/plugins?action=${action}&name=${encodeURIComponent(name)}`, {
        method: "POST",
      });
      if (!res.ok) throw new Error((await res.json()).error);
      const labels = { enable: "enabled", disable: "disabled", reload: "reloaded" };
      toast.success(`${name} ${labels[action]}`);
      fetchPlugins();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Action failed");
    } finally {
      setActionLoading(null);
    }
  };

  const filtered = plugins.filter((p) =>
    p.name.toLowerCase().includes(search.toLowerCase()),
  );

  const enabledCount = plugins.filter((p) => p.isEnabled).length;

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Plugins</h1>
          <p className="text-zinc-400 text-sm mt-1">
            Manage your server plugins
          </p>
        </div>
        <div className="flex items-center gap-3">
          <Badge className="bg-emerald-500/20 text-emerald-400 border-emerald-500/30">
            {enabledCount} / {plugins.length} active
          </Badge>
          <Button
            variant="outline"
            size="sm"
            onClick={fetchPlugins}
            className="border-zinc-700 text-zinc-400 hover:text-white"
          >
            <RefreshCw className="w-4 h-4" />
          </Button>
          <a href="/files?path=plugins" className={buttonVariants({ size: "sm", className: "bg-emerald-600 hover:bg-emerald-500 text-white" })}>
            <Upload className="w-4 h-4 mr-1.5" />
            Upload Plugin
          </a>
        </div>
      </div>

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500" />
        <Input
          placeholder="Search plugins..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9 bg-zinc-900 border-zinc-700 text-white placeholder:text-zinc-500 focus:border-emerald-500/50"
        />
      </div>

      {/* Plugins grid */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <Skeleton key={i} className="h-32 bg-zinc-800 rounded-xl" />
          ))}
        </div>
      ) : filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20 text-zinc-600">
          <Puzzle className="w-10 h-10 mb-3 opacity-50" />
          <p>
            {plugins.length === 0
              ? "No plugins installed"
              : "No plugins match your search"}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
          {filtered.map((plugin) => (
            <Card
              key={plugin.id}
              className={`bg-zinc-900 border-zinc-800 hover:border-zinc-700 transition-colors ${
                !plugin.isEnabled ? "opacity-60" : ""
              }`}
            >
              <CardContent className="p-4">
                <div className="flex items-start justify-between mb-2">
                  <div className="flex items-center gap-2">
                    <div
                      className={`p-1.5 rounded-md ${
                        plugin.isEnabled
                          ? "bg-emerald-500/10"
                          : "bg-zinc-800"
                      }`}
                    >
                      <Puzzle
                        className={`w-4 h-4 ${
                          plugin.isEnabled
                            ? "text-emerald-500"
                            : "text-zinc-500"
                        }`}
                      />
                    </div>
                    <div>
                      <p className="text-sm font-semibold text-white">
                        {plugin.name}
                      </p>
                      {plugin.version && (
                        <p className="text-xs text-zinc-500">
                          v{plugin.version}
                        </p>
                      )}
                    </div>
                  </div>

                  <DropdownMenu>
                    <DropdownMenuTrigger className="inline-flex shrink-0 items-center justify-center rounded-lg text-sm font-medium w-7 h-7 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={() =>
                          handleAction(
                            plugin.name,
                            plugin.isEnabled ? "disable" : "enable",
                          )
                        }
                        className="text-zinc-300 focus:text-white focus:bg-zinc-800"
                        disabled={!!actionLoading}
                      >
                        <Power className="w-4 h-4 mr-2" />
                        {plugin.isEnabled ? "Disable" : "Enable"}
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => handleAction(plugin.name, "reload")}
                        className="text-zinc-300 focus:text-white focus:bg-zinc-800"
                        disabled={!plugin.isEnabled || !!actionLoading}
                      >
                        <RotateCcw className="w-4 h-4 mr-2" />
                        Reload
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>

                {plugin.description && (
                  <p className="text-xs text-zinc-500 line-clamp-2 mb-3">
                    {plugin.description}
                  </p>
                )}

                <div className="flex items-center justify-between mt-3 pt-3 border-t border-zinc-800">
                  <Badge
                    className={
                      plugin.isEnabled
                        ? "bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs"
                        : "bg-zinc-500/20 text-zinc-400 border-zinc-500/30 text-xs"
                    }
                  >
                    {plugin.isEnabled ? "Enabled" : "Disabled"}
                  </Badge>
                  <Switch
                    checked={plugin.isEnabled}
                    disabled={
                      actionLoading === `${plugin.name}-enable` ||
                      actionLoading === `${plugin.name}-disable`
                    }
                    onCheckedChange={(checked) =>
                      handleAction(plugin.name, checked ? "enable" : "disable")
                    }
                    className="scale-75"
                  />
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Jar files not in DB */}
      {jarFiles.filter(
        (jar) => !plugins.find((p) => p.jarFile === jar || p.name + ".jar" === jar),
      ).length > 0 && (
        <Card className="bg-zinc-900 border-zinc-800 border-dashed">
          <CardHeader className="pb-3">
            <CardTitle className="text-sm font-medium text-zinc-500">
              Jar files detected (not yet in database)
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-2">
              {jarFiles.map((jar) => (
                <Badge
                  key={jar}
                  variant="outline"
                  className="border-zinc-700 text-zinc-400 text-xs"
                >
                  {jar}
                </Badge>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
