import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
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 { BrandKitResult } from "./BrandKitResult";
import type { BrandKitBundle } from "./BrandKitResult";

interface BrandKitPanelProps {
  companyId: string;
}

export function BrandKitPanel({ companyId }: BrandKitPanelProps) {
  const [prompt, setPrompt] = useState("");
  const [bundle, setBundle] = useState<BrandKitBundle | 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("brand-kit", { prompt });
  }

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

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">Generate Brand Kit</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="brand-prompt" className="text-sm font-medium">
            Brand description
          </label>
          <Textarea
            id="brand-prompt"
            rows={5}
            placeholder="Describe the brand you want to create — name, industry, style preferences, colors..."
            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 brand kit...
            </>
          ) : (
            "Generate Brand Kit"
          )}
        </Button>

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

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

        {bundle ? (
          <BrandKitResult bundle={bundle} />
        ) : isIdle ? (
          <div className="flex flex-col items-center gap-2 py-8 text-center">
            <p className="text-xl font-semibold">No brand kit yet</p>
            <p className="text-sm text-muted-foreground">
              Describe your brand — name, industry, colors, style — to generate a complete brand
              identity kit including logo, avatars, social images, email templates, and guidelines.
            </p>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
