"use client"

import * as React from "react"
import {
  XIcon,
  Loader2Icon,
  BookmarkIcon,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useRenderState } from "./chat-provider"
import { CompassRenderer } from "@/lib/agent/render/compass-renderer"
import { saveCustomDashboard } from "@/app/actions/dashboards"

export function RenderedView() {
  const {
    spec,
    isRendering,
    error,
    dataContext,
    clearRender,
  } = useRenderState()

  const [saveOpen, setSaveOpen] = React.useState(false)
  const [saveName, setSaveName] = React.useState("")
  const [saving, setSaving] = React.useState(false)

  const hasRoot = !!spec?.root

  const handleSave = async () => {
    if (!saveName.trim() || !spec) return
    setSaving(true)
    const result = await saveCustomDashboard(
      saveName.trim(),
      "",
      JSON.stringify(spec),
      JSON.stringify([]),
      saveName.trim(),
    )
    setSaving(false)
    if (result.success) {
      setSaveOpen(false)
      setSaveName("")
      window.dispatchEvent(
        new CustomEvent("agent-toast", {
          detail: {
            message: `Dashboard "${saveName.trim()}" saved`,
            type: "success",
          },
        })
      )
    } else {
      window.dispatchEvent(
        new CustomEvent("agent-toast", {
          detail: {
            message: result.error,
            type: "error",
          },
        })
      )
    }
  }

  return (
    <div className="flex flex-1 flex-col min-h-0 p-4">
      {/* Header bar */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          {isRendering && (
            <>
              <Loader2Icon className="size-4 animate-spin" />
              <span>Building interface...</span>
            </>
          )}
          {!isRendering && hasRoot && (
            <span>Generated by Slab</span>
          )}
        </div>
        <div className="flex items-center gap-1">
          {hasRoot && !isRendering && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setSaveOpen(true)}
              className="gap-1.5"
            >
              <BookmarkIcon className="size-4" />
              Save as Dashboard
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={clearRender}
            className="gap-1.5"
          >
            <XIcon className="size-4" />
            Clear
          </Button>
        </div>
      </div>

      <Dialog open={saveOpen} onOpenChange={setSaveOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Save as Dashboard</DialogTitle>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="dashboard-name">Name</Label>
              <Input
                id="dashboard-name"
                placeholder="Project Overview"
                value={saveName}
                onChange={(e) =>
                  setSaveName(e.target.value)
                }
                onKeyDown={(e) => {
                  if (e.key === "Enter") handleSave()
                }}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setSaveOpen(false)}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSave}
              disabled={!saveName.trim() || saving}
            >
              {saving ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Rendered content */}
      <div className="flex-1 overflow-auto">
        <div className="mx-auto max-w-6xl">
          {error && (
            <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4 text-sm text-destructive">
              Failed to generate UI: {error.message}
            </div>
          )}

          {!hasRoot && isRendering && (
            <div className="flex items-center justify-center py-12">
              <div className="flex flex-col items-center gap-3 text-muted-foreground">
                <Loader2Icon className="size-8 animate-spin" />
                <span className="text-sm">
                  Generating dashboard...
                </span>
              </div>
            </div>
          )}

          {hasRoot && (
            <CompassRenderer
              spec={spec}
              data={dataContext}
              loading={isRendering}
            />
          )}
        </div>
      </div>
    </div>
  )
}
