import { useState } from "react";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  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 { WallpaperPreview } from "./WallpaperPreview";

export const PLATFORM_DIMENSIONS: Record<string, { width: number; height: number; label: string }> = {
  "desktop-hd":         { width: 2560, height: 1440, label: "Desktop HD (2560 × 1440)" },
  "desktop-fhd":        { width: 1920, height: 1080, label: "Desktop FHD (1920 × 1080)" },
  "desktop-4k":         { width: 3840, height: 2160, label: "Desktop 4K (3840 × 2160)" },
  "mobile-portrait":    { width: 1080, height: 1920, label: "Mobile Portrait (1080 × 1920)" },
  "mobile-landscape":   { width: 1920, height: 1080, label: "Mobile Landscape (1920 × 1080)" },
  "og-image":           { width: 1200, height: 630,  label: "OG Image (1200 × 630)" },
  "twitter-card":       { width: 1200, height: 628,  label: "Twitter Card (1200 × 628)" },
  "instagram-post":     { width: 1080, height: 1080, label: "Instagram Post (1080 × 1080)" },
  "instagram-banner":   { width: 1080, height: 566,  label: "Instagram Banner (1080 × 566)" },
  "linkedin-banner":    { width: 1584, height: 396,  label: "LinkedIn Banner (1584 × 396)" },
  "app-icon":           { width: 1024, height: 1024, label: "App Icon (1024 × 1024)" },
  "favicon":            { width: 32,   height: 32,   label: "Favicon (32 × 32)" },
};

const PLATFORM_GROUPS = [
  {
    label: "Desktop",
    platforms: ["desktop-hd", "desktop-fhd", "desktop-4k"],
  },
  {
    label: "Mobile",
    platforms: ["mobile-portrait", "mobile-landscape"],
  },
  {
    label: "Social",
    platforms: ["og-image", "twitter-card", "instagram-post", "instagram-banner", "linkedin-banner"],
  },
  {
    label: "App",
    platforms: ["app-icon", "favicon"],
  },
];

export type WallpaperBundle = {
  type: "wallpaper-bundle";
  platform: string;
  width: number;
  height: number;
  pngBase64: string;
  prompt: string;
};

export type AppIconBundle = {
  type: "app-icon-bundle";
  sizes: Array<{ size: number; pngBase64: string }>;
  prompt: string;
};

interface WallpaperGeneratePanelProps {
  companyId: string;
}

export function WallpaperGeneratePanel({ companyId }: WallpaperGeneratePanelProps) {
  const [prompt, setPrompt] = useState("");
  const [platform, setPlatform] = useState("desktop-hd");
  const [bundle, setBundle] = useState<WallpaperBundle | AppIconBundle | 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("wallpaper", { prompt, platform });
  }

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

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle className="text-xl font-semibold">Generate Wallpaper</CardTitle>
      </CardHeader>
      <CardContent className="flex flex-col gap-4">
        <div className="flex flex-col gap-2">
          <label htmlFor="wallpaper-prompt" className="text-sm font-medium">
            Describe the scene or concept
          </label>
          <Textarea
            id="wallpaper-prompt"
            rows={4}
            placeholder="Describe the scene, mood, or concept..."
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            disabled={isGenerating}
          />
        </div>

        <div className="flex flex-col gap-2">
          <label htmlFor="wallpaper-platform" className="text-sm font-medium">
            Platform size
          </label>
          <Select value={platform} onValueChange={setPlatform} disabled={isGenerating}>
            <SelectTrigger id="wallpaper-platform" className="w-full">
              <SelectValue placeholder="Select platform" />
            </SelectTrigger>
            <SelectContent>
              {PLATFORM_GROUPS.map((group) => (
                <SelectGroup key={group.label}>
                  <SelectLabel>{group.label}</SelectLabel>
                  {group.platforms.map((key) => {
                    const dim = PLATFORM_DIMENSIONS[key];
                    return (
                      <SelectItem key={key} value={key}>
                        <span className="flex items-center justify-between gap-3 w-full">
                          <span>{dim.label}</span>
                          <span className="text-xs font-mono text-muted-foreground">
                            {dim.width} × {dim.height}
                          </span>
                        </span>
                      </SelectItem>
                    );
                  })}
                </SelectGroup>
              ))}
            </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...
            </>
          ) : (
            "Generate Wallpaper"
          )}
        </Button>

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

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

        {bundle ? (
          <WallpaperPreview bundle={bundle} />
        ) : isIdle ? (
          <div className="flex flex-col items-center gap-2 py-8 text-center">
            <p className="text-xl font-semibold">No image yet</p>
            <p className="text-sm text-muted-foreground">
              Describe a scene or mood and pick a platform size to generate a ready-to-use image.
            </p>
          </div>
        ) : null}
      </CardContent>
    </Card>
  );
}
