import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Progress } from "@/components/ui/progress";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useContentJob } from "@/hooks/useContentJob";
import { getContentJobAsset } from "@/api/contentJobs";
import type { DiagramBundle } from "@/types/content-bundles";
import { DiagramPreview } from "./DiagramPreview";
import { DiagramSourcePanel } from "./DiagramSourcePanel";

const DIAGRAM_TYPES = [
  { value: "architecture", label: "Architecture" },
  { value: "flowchart", label: "Flowchart" },
  { value: "erd", label: "ERD" },
  { value: "sequence", label: "Sequence" },
  { value: "mindmap", label: "Mind Map" },
];

interface DiagramGeneratePanelProps {
  companyId: string;
}

export function DiagramGeneratePanel({ companyId }: DiagramGeneratePanelProps) {
  const [prompt, setPrompt] = useState("");
  const [diagramType, setDiagramType] = useState("flowchart");
  const [bundle, setBundle] = useState<DiagramBundle | null>(null);
  const job = useContentJob(companyId);

  const isGenerating = job.status === "queued" || job.status === "running";
  const isIdle = job.status === "idle";

  async function handleSubmit() {
    if (!prompt.trim() || isGenerating) return;
    setBundle(null);
    await job.submit("diagram", { prompt, diagramType, darkMode: false });
  }

  async function handleRerender(source: string) {
    if (isGenerating) return;
    setBundle(null);
    await job.submit("diagram", { source, diagramType, darkMode: false });
  }

  // Fetch asset when job completes
  if (job.status === "done" && job.resultAssetId && !bundle) {
    void getContentJobAsset(companyId, job.resultAssetId).then(async (assetUrl) => {
      const res = await fetch(assetUrl);
      const text = await res.text();
      try {
        const parsed = JSON.parse(text) as DiagramBundle;
        setBundle(parsed);
      } catch {
        // ignore parse error — will show empty state
      }
    });
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">Generate Diagram</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="diagram-prompt" className="text-sm font-medium">
            Describe your diagram
          </label>
          <Textarea
            id="diagram-prompt"
            rows={4}
            placeholder="Describe an architecture, flow, or sequence..."
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            disabled={isGenerating}
          />
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="diagram-type" className="text-sm font-medium">
            Diagram type
          </label>
          <Select value={diagramType} onValueChange={setDiagramType} disabled={isGenerating}>
            <SelectTrigger id="diagram-type" className="w-full">
              <SelectValue placeholder="Select type" />
            </SelectTrigger>
            <SelectContent>
              {DIAGRAM_TYPES.map((t) => (
                <SelectItem key={t.value} value={t.value}>
                  {t.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Button
          type="button"
          onClick={() => void handleSubmit()}
          disabled={isGenerating || !prompt.trim()}
          className="w-full"
        >
          {isGenerating ? (
            <>
              <Loader2 className="mr-2 size-4 animate-spin" aria-hidden="true" />
              Generating...
            </>
          ) : bundle ? (
            "Generate Diagram"
          ) : (
            "Generate Diagram"
          )}
        </Button>

        {isGenerating && (
          <Progress
            value={job.progress}
            role="progressbar"
            aria-valuenow={job.progress}
            aria-valuemin={0}
            aria-valuemax={100}
            aria-label="Diagram generation progress"
          />
        )}

        {job.status === "failed" && job.errorMessage && (
          <p className="text-sm text-destructive">
            Render failed — {job.errorMessage}. Try again.
          </p>
        )}

        {bundle ? (
          <div className="flex flex-col gap-4">
            {bundle.stripped && (
              <p className="text-sm text-muted-foreground">
                Unsafe directives were removed before rendering.
              </p>
            )}
            <DiagramPreview bundle={bundle} />
            <DiagramSourcePanel
              mermaidSource={bundle.mermaidSource}
              onRerender={(src) => void handleRerender(src)}
            />
          </div>
        ) : isIdle ? (
          <div className="flex flex-col items-center gap-2 py-8 text-center">
            <p className="text-xl font-semibold">No diagram yet</p>
            <p className="text-sm text-muted-foreground">
              Describe an architecture, flow, or sequence and we'll render it.
            </p>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
