import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
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 { Badge } from "@/components/ui/badge";
import { useContentJob } from "@/hooks/useContentJob";
import { getContentJobAsset } from "@/api/contentJobs";

export type PdfDocumentBundle = {
  type: "pdf-document-bundle";
  docType: string;
  title: string;
  pdfBase64: string;
};

const DOC_TYPE_OPTIONS = [
  { value: "report", label: "Report" },
  { value: "invoice", label: "Invoice" },
  { value: "one-pager", label: "One-Pager" },
  { value: "api-docs", label: "API Documentation" },
];

interface DocumentGeneratePanelProps {
  companyId: string;
}

export function DocumentGeneratePanel({ companyId }: DocumentGeneratePanelProps) {
  const [prompt, setPrompt] = useState("");
  const [title, setTitle] = useState("");
  const [docType, setDocType] = useState<"report" | "invoice" | "one-pager" | "api-docs">("report");
  const [bundle, setBundle] = useState<PdfDocumentBundle | 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("pdf-document", { docType, prompt, title: title.trim() || docType });
  }

  // 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 PdfDocumentBundle;
        setBundle(parsed);
      } catch {
        // ignore parse error — will show empty state
      }
    });
  }

  function handleDownloadPdf() {
    if (!bundle) return;
    const bytes = Uint8Array.from(atob(bundle.pdfBase64), (c) => c.charCodeAt(0));
    const blob = new Blob([bytes], { type: "application/pdf" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${bundle.title || bundle.docType}.pdf`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">Generate Document</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="doc-type" className="text-sm font-medium">
            Document type
          </label>
          <Select
            value={docType}
            onValueChange={(v) => setDocType(v as typeof docType)}
            disabled={isGenerating}
          >
            <SelectTrigger id="doc-type" className="w-full">
              <SelectValue placeholder="Select document type" />
            </SelectTrigger>
            <SelectContent>
              {DOC_TYPE_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="doc-title" className="text-sm font-medium">
            Title
          </label>
          <Input
            id="doc-title"
            placeholder="e.g. Q3 Financial Report"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            disabled={isGenerating}
          />
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="doc-prompt" className="text-sm font-medium">
            Content description
          </label>
          <Textarea
            id="doc-prompt"
            rows={5}
            placeholder="Describe the content, data, or topic to include in the document..."
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            disabled={isGenerating}
          />
        </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...
            </>
          ) : (
            "Generate PDF"
          )}
        </Button>

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

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

        {bundle ? (
          <div className="flex flex-col gap-3 rounded-lg border border-border bg-card p-4">
            <div className="flex items-center gap-2">
              <span className="text-sm font-medium">{bundle.title || bundle.docType}</span>
              <Badge variant="secondary">{bundle.docType}</Badge>
            </div>
            <Button
              type="button"
              variant="default"
              className="w-full"
              onClick={handleDownloadPdf}
            >
              Download PDF
            </Button>
          </div>
        ) : isIdle ? (
          <div className="flex flex-col items-center gap-2 py-8 text-center">
            <p className="text-xl font-semibold">No document yet</p>
            <p className="text-sm text-muted-foreground">
              Select a document type, enter a title and description, then click Generate PDF.
            </p>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
