"use client"

import { useState } from "react"
import { usePlugins, useManagePlugin } from "@/hooks/use-plugins"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Switch } from "@/components/ui/switch"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Spinner } from "@/components/ui/spinner"
import { toast } from "sonner"

export default function PluginsPage() {
  const { data: plugins, isLoading } = usePlugins()
  const manage = useManagePlugin()
  const [name, setName] = useState("")
  const [pluginType, setPluginType] = useState("media_processor")

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      await manage.mutateAsync({
        action: "create",
        name,
        plugin_type: pluginType,
      })
      setName("")
      toast.success("Plugin created")
    } catch {
      toast.error("Failed to create plugin")
    }
  }

  const handleToggle = async (pluginId: string, enabled: boolean) => {
    try {
      await manage.mutateAsync({
        action: enabled ? "enable" : "disable",
        plugin_id: pluginId,
      })
      toast.success(enabled ? "Plugin enabled" : "Plugin disabled")
    } catch {
      toast.error("Failed to update plugin")
    }
  }

  return (
    <div className="flex flex-col gap-6">
      <h1 className="text-lg font-semibold">Plugin Management</h1>

      <Card>
        <CardHeader>
          <CardTitle>Installed Plugins</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <Spinner />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Type</TableHead>
                  <TableHead>Enabled</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(plugins ?? []).map((p) => (
                  <TableRow key={p.plugin_id}>
                    <TableCell className="font-mono text-sm">
                      {p.name}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{p.plugin_type}</Badge>
                    </TableCell>
                    <TableCell>
                      <Switch
                        checked={p.is_enabled}
                        onCheckedChange={(checked) =>
                          handleToggle(p.plugin_id, checked)
                        }
                      />
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Create Plugin</CardTitle>
          <CardDescription>Register a new processing plugin</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleCreate} className="flex items-end gap-2">
            <div className="flex flex-col gap-1">
              <Label className="text-xs">Name</Label>
              <Input
                required
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="my-processor"
                className="h-8"
              />
            </div>
            <div className="flex flex-col gap-1">
              <Label className="text-xs">Type</Label>
              <Input
                required
                value={pluginType}
                onChange={(e) => setPluginType(e.target.value)}
                placeholder="media_processor"
                className="h-8"
              />
            </div>
            <Button type="submit" size="sm" disabled={manage.isPending}>
              Create
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
