"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/hooks/use-toast";
import {
  Settings2, Mail, RefreshCw, Loader2, Trash2, Crown, BarChart3, TrendingUp, Building2, CalendarCheck, MousePointerClick,
} from "lucide-react";
import type { Brand, Campaign, Workspace } from "./types";
import { parseServices } from "./types";

interface SettingsViewProps {
  workspace: Workspace | null;
  brands: Brand[];
  campaigns: Campaign[];
  onPlanSwitch: (plan: string) => void;
  onRefresh: () => void;
  onDeleteBrand: (id: string) => void;
}

export default function SettingsView({ workspace, brands, campaigns, onPlanSwitch, onRefresh, onDeleteBrand }: SettingsViewProps) {
  const { toast } = useToast();
  const [brief, setBrief] = useState<string | null>(null);
  const [briefLoading, setBriefLoading] = useState(false);

  const activeBrand = brands[0];

  async function loadBrief() {
    if (!activeBrand) return;
    setBriefLoading(true);
    try {
      const res = await fetch(`/api/brief?brandId=${activeBrand.id}`);
      const data = await res.json();
      setBrief(data.brief || "Add a brand to get weekly briefs.");
    } catch {
      setBrief("Could not load the brief. Try again.");
    } finally {
      setBriefLoading(false);
    }
  }

  useEffect(() => {
    if (activeBrand && brief === null) loadBrief();
  }, [activeBrand?.id]);

  const totalCreatives = campaigns.reduce((n, c) => n + c.creatives.length, 0);
  const approved = workspace?.usage.approvedCount ?? 0;
  const scheduled = workspace?.usage.scheduledCount ?? 0;
  const approvalRate = totalCreatives > 0 ? Math.round((approved / totalCreatives) * 100) : 0;

  if (!workspace) return null;
  const plan = workspace.plan;
  const cap = workspace.usage.creativeCap;

  return (
    <div className="mx-auto grid w-full max-w-6xl gap-6 px-4 py-6 lg:grid-cols-2">
      {/* LEFT column */}
      <div className="space-y-6">
        {/* plan card */}
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between">
            <h2 className="flex items-center gap-2 font-bold"><Crown className="h-4 w-4 text-orange-600" /> Subscription</h2>
            <Badge className="bg-orange-100 text-orange-800 hover:bg-orange-100">{plan.name} plan — ${plan.price}/mo</Badge>
          </div>
          <p className="mt-2 text-sm text-stone-500">Switch plans instantly to explore what each tier unlocks (demo billing).</p>
          <div className="mt-4 grid gap-2 sm:grid-cols-3">
            {workspace.plans.map((p) => (
              <button
                key={p.id}
                onClick={() => onPlanSwitch(p.id)}
                className={`rounded-xl border p-3 text-left transition-all ${p.id === plan.id ? "border-orange-400 bg-orange-50 ring-1 ring-orange-300" : "border-stone-200 bg-white hover:border-stone-300"}`}
              >
                <p className="text-sm font-bold">{p.name}</p>
                <p className="text-xs text-stone-500">${p.price}/mo</p>
                <p className="mt-1 text-[10px] text-stone-400">{p.maxBrands} brand{p.maxBrands > 1 ? "s" : ""} · {p.monthlyCreatives === null ? "unlimited" : p.monthlyCreatives} creatives</p>
              </button>
            ))}
          </div>
        </div>

        {/* usage */}
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <h2 className="flex items-center gap-2 font-bold"><BarChart3 className="h-4 w-4 text-orange-600" /> This month</h2>
          <div className="mt-4 space-y-4">
            <div>
              <div className="mb-1 flex justify-between text-sm">
                <span className="text-stone-600">AI creatives</span>
                <span className="font-semibold">{workspace.usage.monthlyCreatives}{cap !== null ? ` / ${cap}` : " · unlimited"}</span>
              </div>
              {cap !== null && (
                <Progress value={Math.min(100, (workspace.usage.monthlyCreatives / cap) * 100)} className="h-2" />
              )}
            </div>
            <div>
              <div className="mb-1 flex justify-between text-sm">
                <span className="text-stone-600">Brands</span>
                <span className="font-semibold">{workspace.usage.brands} / {plan.maxBrands}</span>
              </div>
              <Progress value={(workspace.usage.brands / plan.maxBrands) * 100} className="h-2" />
            </div>
            <div className="grid grid-cols-3 gap-2 pt-1">
              {[
                { icon: MousePointerClick, label: "Generated", value: totalCreatives },
                { icon: CalendarCheck, label: "Scheduled", value: scheduled },
                { icon: TrendingUp, label: "Approval rate", value: `${approvalRate}%` },
              ].map((s) => (
                <div key={s.label} className="rounded-xl bg-stone-50 p-3 text-center">
                  <s.icon className="mx-auto h-4 w-4 text-stone-400" />
                  <p className="mt-1 text-lg font-bold">{s.value}</p>
                  <p className="text-[10px] uppercase tracking-wide text-stone-400">{s.label}</p>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* brands */}
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <div className="flex items-center justify-between">
            <h2 className="flex items-center gap-2 font-bold"><Building2 className="h-4 w-4 text-orange-600" /> Brands</h2>
            <Button size="sm" variant="outline" onClick={onRefresh}><RefreshCw className="mr-1 h-3 w-3" /> Refresh</Button>
          </div>
          <ScrollArea className="mt-3 max-h-56">
            <div className="space-y-2">
              {brands.length === 0 && <p className="py-4 text-center text-sm text-stone-400">No brands yet — add one from the Studio tab.</p>}
              {brands.map((b) => (
                <div key={b.id} className="flex items-center gap-3 rounded-xl border border-stone-200 p-3">
                  <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg text-xs font-bold text-white" style={{ background: `linear-gradient(135deg, ${b.primaryColor}, ${b.secondaryColor})` }}>
                    {b.logoText}
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-semibold">{b.name}</p>
                    <p className="truncate text-xs text-stone-500">{parseServices(b).slice(0, 3).join(" · ") || b.description}</p>
                  </div>
                  <Button size="sm" variant="ghost" className="h-8 w-8 shrink-0 p-0 text-stone-400 hover:text-red-600" onClick={() => onDeleteBrand(b.id)} title="Delete brand">
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              ))}
            </div>
          </ScrollArea>
        </div>
      </div>

      {/* RIGHT column: weekly brief */}
      <div className="space-y-6">
        <div className="overflow-hidden rounded-2xl border border-stone-200 bg-white shadow-sm">
          <div className="flex items-center justify-between border-b border-stone-100 bg-gradient-to-r from-orange-50 to-amber-50 px-6 py-4">
            <div>
              <h2 className="flex items-center gap-2 font-bold"><Mail className="h-4 w-4 text-orange-600" /> Monday Morning Brief</h2>
              <p className="text-xs text-stone-500">Every Monday 8:00 AM — emailed automatically. This is your inbox preview.</p>
            </div>
            <Button size="sm" variant="outline" onClick={loadBrief} disabled={briefLoading || !activeBrand}>
              {briefLoading ? <Loader2 className="mr-1 h-3 w-3 animate-spin" /> : <RefreshCw className="mr-1 h-3 w-3" />} Regenerate
            </Button>
          </div>
          <div className="p-6">
            {!activeBrand ? (
              <p className="py-8 text-center text-sm text-stone-400">Add a brand to start receiving weekly briefs.</p>
            ) : (
              <>
                <div className="mb-4 flex items-center gap-3 rounded-xl bg-stone-50 p-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg text-xs font-bold text-white" style={{ background: `linear-gradient(135deg, ${activeBrand.primaryColor}, ${activeBrand.secondaryColor})` }}>
                    {activeBrand.logoText}
                  </div>
                  <div>
                    <p className="text-sm font-semibold">To: you@{activeBrand.name.toLowerCase().replace(/[^a-z0-9]/g, "") || "business"}.com</p>
                    <p className="text-xs text-stone-500">Subject: 5 new ad concepts for {activeBrand.name} — approve in 30 seconds</p>
                  </div>
                </div>
                {briefLoading && !brief ? (
                  <div className="space-y-2 py-4">
                    {[...Array(6)].map((_, i) => <div key={i} className="h-4 animate-pulse rounded bg-stone-100" style={{ width: `${90 - i * 8}%` }} />)}
                  </div>
                ) : (
                  <pre className="whitespace-pre-wrap font-sans text-sm leading-relaxed text-stone-700">{brief}</pre>
                )}
                <Button
                  className="mt-5 w-full bg-orange-600 hover:bg-orange-700"
                  onClick={() => toast({ title: "In the full product", description: "This button deep-links into the Approve & Schedule calendar." })}
                >
                  Approve & post in 30 seconds →
                </Button>
              </>
            )}
          </div>
        </div>

        {/* connected accounts (plan gated) */}
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <h2 className="flex items-center gap-2 font-bold"><Settings2 className="h-4 w-4 text-orange-600" /> Integrations</h2>
          <p className="mt-1 text-xs text-stone-500">
            Organic auto-publishing works today. Paid campaign launching unlocks after platform API reviews (Meta, TikTok, LinkedIn, X) — the app ships organic-first by design.
          </p>
          <div className="mt-4 space-y-2">
            {[
              { name: "Meta (Instagram + Facebook)", status: "Connected · organic auto-post", ok: true },
              { name: "TikTok Content API", status: "Connected · organic auto-post", ok: true },
              { name: "LinkedIn (Walled Garden API)", status: "Connected · organic auto-post", ok: true },
              { name: "X API v2", status: plan.apiPriority ? "Connected · priority queue" : "Pending approval", ok: plan.apiPriority },
              { name: "Meta Ads Manager (paid launching)", status: plan.price >= 59 ? "Ready · boosted posts enabled" : "Growth plan required", ok: plan.price >= 59 },
            ].map((row) => (
              <div key={row.name} className="flex items-center justify-between rounded-xl border border-stone-100 bg-stone-50 px-3 py-2.5">
                <div>
                  <p className="text-sm font-medium">{row.name}</p>
                  <p className="text-xs text-stone-500">{row.status}</p>
                </div>
                <span className={`h-2.5 w-2.5 rounded-full ${row.ok ? "bg-emerald-500" : "bg-amber-400"}`} />
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}
