import { useState, useMemo, useEffect } from "react";
import { Loader2, Download, Video } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useContentJob } from "@/hooks/useContentJob";
import { getContentJobAsset } from "@/api/contentJobs";

interface PresentationBundle {
  type: "presentation-bundle";
  presentationType: "pitch-deck" | "demo-video";
  title: string;
  slideCount: number;
  durationInFrames: number;
  fps: number;
  mp4Base64: string;
  inputProps: Record<string, unknown>;
}

interface PresentationPanelProps {
  companyId: string;
}

export function PresentationPanel({ companyId }: PresentationPanelProps) {
  const [prompt, setPrompt] = useState("");
  const [videoType, setVideoType] = useState<"pitch-deck" | "demo-video">("pitch-deck");
  const [bundle, setBundle] = useState<PresentationBundle | 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("presentation", { prompt, videoType, title: prompt.slice(0, 60) });
  }

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

  const videoUrl = useMemo(() => {
    if (!bundle?.mp4Base64) return null;
    const bytes = Uint8Array.from(atob(bundle.mp4Base64), (c) => c.charCodeAt(0));
    return URL.createObjectURL(new Blob([bytes], { type: "video/mp4" }));
  }, [bundle?.mp4Base64]);

  useEffect(() => {
    return () => {
      if (videoUrl) URL.revokeObjectURL(videoUrl);
    };
  }, [videoUrl]);

  function handleGenerateAnother() {
    job.reset();
    setBundle(null);
    setPrompt("");
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">Generate Presentation</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="presentation-prompt" className="text-sm font-medium">
            Presentation description
          </label>
          <Textarea
            id="presentation-prompt"
            rows={5}
            placeholder="Describe the presentation you want — topic, audience, key points..."
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            disabled={isGenerating}
          />
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="video-type" className="text-sm font-medium">
            Presentation type
          </label>
          <Select
            value={videoType}
            onValueChange={(v) => setVideoType(v as "pitch-deck" | "demo-video")}
            disabled={isGenerating}
          >
            <SelectTrigger id="video-type" className="w-full">
              <SelectValue placeholder="Select type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="pitch-deck">Pitch Deck</SelectItem>
              <SelectItem value="demo-video">Demo Video</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 presentation...
            </>
          ) : (
            "Generate Presentation"
          )}
        </Button>

        {(job.status === "queued" || job.status === "running") && (
          <div className="flex flex-col gap-1">
            <Progress
              value={job.progress}
              role="progressbar"
              aria-valuenow={job.progress}
              aria-valuemin={0}
              aria-valuemax={100}
              aria-label="Presentation render progress"
            />
            <p className="text-xs text-muted-foreground text-right">{job.progress}%</p>
          </div>
        )}

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

        {bundle && videoUrl ? (
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-1">
              <p className="text-base font-semibold">{bundle.title}</p>
              <p className="text-sm text-muted-foreground">
                {bundle.slideCount} slides &middot; {bundle.presentationType === "pitch-deck" ? "Pitch Deck" : "Demo Video"}
              </p>
            </div>

            <video
              src={videoUrl}
              controls
              className="w-full rounded-lg aspect-video"
            />

            <div className="flex gap-2">
              <Button asChild variant="outline" className="flex-1">
                <a href={videoUrl} download={`${bundle.title}.mp4`}>
                  <Download className="mr-2 size-4" aria-hidden="true" />
                  Download MP4
                </a>
              </Button>
              <Button
                type="button"
                variant="secondary"
                className="flex-1"
                onClick={handleGenerateAnother}
              >
                <Video className="mr-2 size-4" aria-hidden="true" />
                Generate Another
              </Button>
            </div>
          </div>
        ) : isIdle ? (
          <div className="flex flex-col items-center gap-2 py-8 text-center">
            <p className="text-xl font-semibold">No presentation yet</p>
            <p className="text-sm text-muted-foreground">
              Describe your presentation — topic, audience, key points — to generate a pitch deck
              or demo video rendered as an MP4.
            </p>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
