"use client"

import { useState } from "react"
import { usePipelines, useConfigurePipeline } from "@/hooks/use-pipelines"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
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 PipelinesPage() {
  const { data: pipelines, isLoading } = usePipelines()
  const configure = useConfigurePipeline()
  const [triggerEvent, setTriggerEvent] = useState("")
  const [stepsJson, setStepsJson] = useState("[]")

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const steps = JSON.parse(stepsJson)
      await configure.mutateAsync({ trigger_event: triggerEvent, steps })
      toast.success("Pipeline configured")
    } catch {
      toast.error("Failed — check JSON syntax")
    }
  }

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

      <Card>
        <CardHeader>
          <CardTitle>Pipelines</CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <Spinner />
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Trigger Event</TableHead>
                  <TableHead>Steps</TableHead>
                  <TableHead>ID</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(pipelines ?? []).map((p) => (
                  <TableRow key={p.pipeline_id}>
                    <TableCell className="font-mono text-sm">
                      {p.trigger_event}
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary">{p.steps_count}</Badge>
                    </TableCell>
                    <TableCell className="font-mono text-xs text-muted-foreground">
                      {p.pipeline_id.slice(0, 8)}...
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Configure Pipeline</CardTitle>
          <CardDescription>
            Define a processing pipeline triggered by an event
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="flex flex-col gap-3">
            <div className="flex flex-col gap-1">
              <Label className="text-xs">Trigger Event</Label>
              <Input
                required
                value={triggerEvent}
                onChange={(e) => setTriggerEvent(e.target.value)}
                placeholder="asset.ingested"
                className="h-8"
              />
            </div>
            <div className="flex flex-col gap-1">
              <Label className="text-xs">
                Steps (JSON array of {`{ plugin_id, config }`})
              </Label>
              <Textarea
                value={stepsJson}
                onChange={(e) => setStepsJson(e.target.value)}
                rows={4}
                className="font-mono text-xs"
              />
            </div>
            <Button
              type="submit"
              size="sm"
              className="self-start"
              disabled={configure.isPending}
            >
              Save Pipeline
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
