"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/hooks/use-toast";
import {
  Sparkles, Loader2, Megaphone, HeartHandshake, DollarSign, MapPin, Target,
  Check, Copy, ThumbsUp, ThumbsDown, Video, Lock,
} from "lucide-react";
import type { Brand, Campaign } from "./types";
import { CHANNEL_META, FORMAT_LABEL, parseServices } from "./types";

interface StudioViewProps {
  brands: Brand[];
  selectedBrandId: string | null;
  onSelectBrand: (id: string) => void;
  onCampaignCreated: (campaign: Campaign) => void;
  planName: string;
  monthlyCreatives: number;
  creativeCap: number | null;
}

const IDEA_CHIPS = [
  "Weekend special to fill slow hours",
  "New customer first-visit offer",
  "Holiday season gift ideas",
  "Behind-the-scenes of our process",
  "Customer appreciation week",
];

export default function StudioView({
  brands, selectedBrandId, onSelectBrand, onCampaignCreated,
  planName, monthlyCreatives, creativeCap,
}: StudioViewProps) {
  const { toast } = useToast();
  const [prompt, setPrompt] = useState("");
  const [mode, setMode] = useState<"ORGANIC" | "PAID">("ORGANIC");
  const [objective, setObjective] = useState("CLICKS");
  const [budget, setBudget] = useState("5");
  const [location, setLocation] = useState("");
  const [generating, setGenerating] = useState(false);
  const [result, setResult] = useState<Campaign | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);

  const brand = brands.find((b) => b.id === selectedBrandId) || null;
  const capReached = creativeCap !== null && monthlyCreatives >= creativeCap;

  async function generate() {
    if (!brand) {
      toast({ title: "Pick a brand first", description: "Select or create a brand to generate campaigns." });
      return;
    }
    if (!prompt.trim()) {
      toast({ title: "Describe what to promote", description: "One line is enough — e.g. \"weekend bakery special\"." });
      return;
    }
    setGenerating(true);
    setResult(null);
    try {
      const res = await fetch("/api/campaigns", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          brandId: brand.id, prompt, mode, objective,
          dailyBudget: Number(budget), targetLocation: location,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        toast({ title: "Generation failed", description: data.error || "Please try again." });
        return;
      }
      setResult(data.campaign);
      onCampaignCreated(data.campaign);
      toast({
        title: "Campaign ready 🎉",
        description: `${data.campaign.creatives.length} channel-native creatives generated.`,
      });
    } catch {
      toast({ title: "Network error", description: "Please try again." });
    } finally {
      setGenerating(false);
    }
  }

  function copyText(id: string, text: string) {
    navigator.clipboard?.writeText(text).then(() => {
      setCopiedId(id);
      setTimeout(() => setCopiedId(null), 1500);
    });
  }

  if (!brand && brands.length === 0) {
    return (
      <div className="flex h-[60vh] flex-col items-center justify-center px-4 text-center">
        <Megaphone className="mb-4 h-12 w-12 text-stone-300" />
        <h2 className="text-xl font-semibold">No brands yet</h2>
        <p className="mt-1 max-w-sm text-sm text-stone-500">
          Add your first brand with a URL or one-line description — then generate campaigns in seconds.
        </p>
      </div>
    );
  }

  return (
    <div className="mx-auto grid w-full max-w-6xl gap-6 px-4 py-6 lg:grid-cols-[380px_1fr]">
      {/* LEFT: composer */}
      <div className="space-y-4">
        <div className="rounded-2xl border border-stone-200 bg-white p-5 shadow-sm">
          <h2 className="mb-4 flex items-center gap-2 font-semibold">
            <Sparkles className="h-4 w-4 text-orange-600" /> Campaign composer
          </h2>

          {/* brand select */}
          <label className="text-xs font-medium uppercase tracking-wide text-stone-400">Brand</label>
          <Select value={selectedBrandId ?? undefined} onValueChange={onSelectBrand}>
            <SelectTrigger className="mt-1 w-full">
              <SelectValue placeholder="Choose a brand" />
            </SelectTrigger>
            <SelectContent>
              {brands.map((b) => (
                <SelectItem key={b.id} value={b.id}>
                  <span className="flex items-center gap-2">
                    <span className="flex h-5 w-5 items-center justify-center rounded text-[10px] font-bold text-white" style={{ background: b.primaryColor }}>
                      {b.logoText}
                    </span>
                    {b.name}
                  </span>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* mode toggle */}
          <div className="mt-4 flex items-center justify-between rounded-xl border border-stone-200 bg-stone-50 px-3 py-2.5">
            <div className="flex items-center gap-2">
              {mode === "ORGANIC" ? <HeartHandshake className="h-4 w-4 text-emerald-600" /> : <DollarSign className="h-4 w-4 text-orange-600" />}
              <span className="text-sm font-medium">{mode === "ORGANIC" ? "Organic posts" : "Paid campaign"}</span>
            </div>
            <Switch
              checked={mode === "PAID"}
              onCheckedChange={(v) => setMode(v ? "PAID" : "ORGANIC")}
              aria-label="Toggle paid mode"
            />
          </div>
          <p className="mt-1.5 text-xs text-stone-500">
            {mode === "ORGANIC"
              ? "Posts go straight to your feeds via connected accounts."
              : "Boosted posts — just 3 choices, no ad-manager maze."}
          </p>

          {/* paid options */}
          {mode === "PAID" && (
            <div className="mt-3 space-y-3 rounded-xl border border-orange-200 bg-orange-50 p-3">
              <div>
                <label className="flex items-center gap-1 text-xs font-medium text-stone-600">
                  <Target className="h-3 w-3" /> Objective
                </label>
                <Select value={objective} onValueChange={setObjective}>
                  <SelectTrigger className="mt-1 h-9 w-full bg-white"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CALLS">More calls</SelectItem>
                    <SelectItem value="CLICKS">More website clicks</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <label className="flex items-center gap-1 text-xs font-medium text-stone-600">
                  <DollarSign className="h-3 w-3" /> Daily budget: ${budget}/day
                </label>
                <Input type="range" min="5" max="50" step="5" value={budget} onChange={(e) => setBudget(e.target.value)} className="mt-1 accent-orange-600" />
              </div>
              <div>
                <label className="flex items-center gap-1 text-xs font-medium text-stone-600">
                  <MapPin className="h-3 w-3" /> Target location
                </label>
                <Input value={location} onChange={(e) => setLocation(e.target.value)} placeholder="e.g. Downtown + 10 miles" className="mt-1 h-9 bg-white" />
              </div>
            </div>
          )}

          {/* prompt */}
          <label className="mt-4 block text-xs font-medium uppercase tracking-wide text-stone-400">
            What do you want to promote?
          </label>
          <Textarea
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder='One line is enough — "weekend bakery special"'
            rows={3}
            className="mt-1 resize-none"
          />
          <div className="mt-2 flex flex-wrap gap-1.5">
            {IDEA_CHIPS.map((chip) => (
              <button
                key={chip}
                onClick={() => setPrompt(chip)}
                className="rounded-full border border-stone-200 bg-stone-50 px-2.5 py-1 text-[11px] text-stone-600 transition-colors hover:border-orange-300 hover:text-orange-700"
              >
                {chip}
              </button>
            ))}
          </div>

          <Button onClick={generate} disabled={generating || capReached || !brand} className="mt-4 h-11 w-full bg-orange-600 text-base font-semibold hover:bg-orange-700">
            {generating ? (
              <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Expanding with AIDA + writing…</>
            ) : capReached ? (
              <><Lock className="mr-2 h-4 w-4" /> Monthly creative cap reached</>
            ) : (
              <><Sparkles className="mr-2 h-4 w-4" /> Generate campaign</>
            )}
          </Button>
          <p className="mt-2 text-center text-xs text-stone-400">
            {creativeCap !== null
              ? `${monthlyCreatives}/${creativeCap} creatives used this month · ${planName} plan`
              : `Unlimited creatives · ${planName} plan`}
          </p>
        </div>

        {/* brand card */}
        {brand && (
          <div className="rounded-2xl border border-stone-200 bg-white p-5 shadow-sm">
            <div className="flex items-center gap-3">
              <div className="flex h-11 w-11 items-center justify-center rounded-xl text-sm font-bold text-white" style={{ background: `linear-gradient(135deg, ${brand.primaryColor}, ${brand.secondaryColor})` }}>
                {brand.logoText}
              </div>
              <div>
                <p className="font-semibold">{brand.name}</p>
                <p className="text-xs text-stone-500">{brand.city || "Local business"}</p>
              </div>
            </div>
            <p className="mt-3 text-xs leading-relaxed text-stone-600">{brand.description}</p>
            <div className="mt-3 flex flex-wrap gap-1.5">
              {parseServices(brand).slice(0, 4).map((s) => (
                <Badge key={s} variant="outline" className="border-stone-200 text-[11px] font-normal text-stone-600">{s}</Badge>
              ))}
            </div>
            <div className="mt-3 flex items-center gap-2 text-[11px] text-stone-400">
              <span>Tone:</span> <span className="font-medium text-stone-600">{brand.tone}</span>
            </div>
          </div>
        )}
      </div>

      {/* RIGHT: results */}
      <div>
        {generating && (
          <div className="grid gap-4 sm:grid-cols-2">
            {[0, 1, 2, 3].map((i) => (
              <div key={i} className="animate-pulse rounded-2xl border border-stone-200 bg-white p-5">
                <div className="h-5 w-24 rounded bg-stone-200" />
                <div className="mt-3 h-4 w-3/4 rounded bg-stone-100" />
                <div className="mt-2 h-16 w-full rounded bg-stone-100" />
              </div>
            ))}
          </div>
        )}

        {!generating && !result && (
          <div className="flex h-full min-h-[400px] flex-col items-center justify-center rounded-2xl border-2 border-dashed border-stone-200 bg-stone-100/40 px-6 text-center">
            <div className="flex -space-x-2">
              {["bg-pink-500", "bg-fuchsia-500", "bg-sky-600", "bg-neutral-900", "bg-blue-500"].map((c, i) => (
                <div key={i} className={`flex h-9 w-9 items-center justify-center rounded-full border-2 border-white text-xs font-bold text-white ${c}`}>
                  {Object.values(CHANNEL_META)[i].icon}
                </div>
              ))}
            </div>
            <h3 className="mt-4 text-lg font-semibold text-stone-700">Your campaign package appears here</h3>
            <p className="mt-1 max-w-sm text-sm text-stone-500">
              One prompt becomes a coordinated Instagram post + story, TikTok script, LinkedIn article-style post, X one-liner and Facebook update — each natively formatted.
            </p>
          </div>
        )}

        {!generating && result && (
          <ScrollArea className="h-[calc(100vh-160px)] pr-2">
            <div className="mb-4 flex items-center justify-between">
              <div>
                <h2 className="text-lg font-bold">{result.name}</h2>
                <p className="text-xs text-stone-500">
                  {result.mode === "PAID"
                    ? `Paid · ${result.objective === "CALLS" ? "More calls" : "Website clicks"} · $${result.dailyBudget}/day${result.targetLocation ? ` · ${result.targetLocation}` : ""}`
                    : "Organic package · 5 channels"}
                </p>
              </div>
              <Badge className="bg-emerald-100 text-emerald-700 hover:bg-emerald-100">Ready to review</Badge>
            </div>
            <div className="grid gap-4 pb-6 sm:grid-cols-2">
              {result.creatives.map((c) => {
                const meta = CHANNEL_META[c.channel];
                const preview = [c.caption || c.body, c.hashtags].filter(Boolean).join("\n\n");
                return (
                  <div key={c.id} className="flex flex-col rounded-2xl border border-stone-200 bg-white p-5 shadow-sm transition-shadow hover:shadow-md">
                    <div className="mb-3 flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <span className={`inline-flex items-center gap-1.5 rounded-md border px-2 py-0.5 text-[11px] font-semibold ${meta.chip}`}>
                          <span>{meta.icon}</span> {meta.label}
                        </span>
                        <Badge variant="outline" className="border-stone-200 text-[10px] font-normal text-stone-500">
                          {FORMAT_LABEL[c.format] || c.format} · {meta.ratio}
                        </Badge>
                      </div>
                      <button onClick={() => copyText(c.id, preview)} className="text-stone-400 transition-colors hover:text-stone-700" title="Copy">
                        {copiedId === c.id ? <Check className="h-4 w-4 text-emerald-600" /> : <Copy className="h-4 w-4" />}
                      </button>
                    </div>
                    {c.headline && <p className="text-sm font-bold leading-snug">{c.headline}</p>}
                    {c.hook && (
                      <p className="mt-1 text-xs font-semibold text-fuchsia-700">Hook: “{c.hook}”</p>
                    )}
                    <p className="mt-1.5 whitespace-pre-wrap text-sm leading-relaxed text-stone-700">{c.caption || c.body}</p>
                    {c.hashtags && <p className="mt-1.5 text-xs leading-relaxed text-pink-600">{c.hashtags}</p>}
                    {c.videoScript && (
                      <div className="mt-2 rounded-lg border border-fuchsia-200 bg-fuchsia-50 p-2.5">
                        <p className="flex items-center gap-1 text-[11px] font-semibold text-fuchsia-700"><Video className="h-3 w-3" /> Video script</p>
                        <p className="mt-1 whitespace-pre-wrap text-xs leading-relaxed text-fuchsia-900">{c.videoScript}</p>
                      </div>
                    )}
                    {c.cta && (
                      <p className="mt-auto pt-3 text-xs font-semibold text-orange-700">CTA: {c.cta}</p>
                    )}
                  </div>
                );
              })}
            </div>
            <div className="mb-6 flex items-center justify-center gap-2 rounded-xl border border-stone-200 bg-white p-3 text-sm text-stone-600">
              <ThumbsUp className="h-4 w-4 text-emerald-600" /> Happy with it?
              <span className="mx-1 text-stone-300">|</span>
              Next: <strong className="mx-1">Calendar</strong> tab → review on the week → “Schedule All”
              <ThumbsDown className="ml-2 h-4 w-4 text-stone-300" />
            </div>
          </ScrollArea>
        )}
      </div>
    </div>
  );
}
