"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Globe2, Sparkles, Check, Pencil, ArrowRight, Store, Loader2 } from "lucide-react";
import type { Brand } from "./types";

interface OnboardingProps {
  onDone: (brand: Brand) => void;
  onSkip: () => void;
  hasBrands: boolean;
}

interface ExtractionState {
  step: "input" | "loading" | "review";
  detectedVia: "url" | "description" | null;
  brand: Brand | null;
}

const EXAMPLES = [
  "https://rosabakery.com",
  "Bella's Hair Salon — cuts, color and bridal styling downtown",
  "https://ironhouse.fitness",
];

export default function Onboarding({ onDone, onSkip, hasBrands }: OnboardingProps) {
  const [input, setInput] = useState("");
  const [state, setState] = useState<ExtractionState>({ step: "input", detectedVia: null, brand: null });
  const [error, setError] = useState<string | null>(null);
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [draft, setDraft] = useState({ name: "", description: "", tone: "", audience: "", services: "" });

  async function extract(value?: string) {
    const v = (value ?? input).trim();
    if (!v) {
      setError("Enter a website URL or a one-line business description.");
      return;
    }
    setError(null);
    setState({ step: "loading", detectedVia: null, brand: null });
    try {
      const res = await fetch("/api/brands", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ input: v }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Something went wrong.");
        setState({ step: "input", detectedVia: null, brand: null });
        return;
      }
      setDraft({
        name: data.brand.name,
        description: data.brand.description,
        tone: data.brand.tone,
        audience: data.brand.audience || "",
        services: (JSON.parse(data.brand.services || "[]") as string[]).join("\n"),
      });
      setState({ step: "review", detectedVia: data.detectedVia, brand: data.brand });
      setEditing(false);
    } catch {
      setError("Network error — please try again.");
      setState({ step: "input", detectedVia: null, brand: null });
    }
  }

  async function save() {
    if (!state.brand) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/brands?id=${state.brand.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: draft.name,
          description: draft.description,
          tone: draft.tone,
          audience: draft.audience,
          services: draft.services.split("\n").map((s) => s.trim()).filter(Boolean),
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "Could not save brand.");
        setSaving(false);
        return;
      }
      onDone(data.brand as Brand);
    } catch {
      setError("Network error — please try again.");
      setSaving(false);
    }
  }

  return (
    <div className="mx-auto w-full max-w-2xl px-4 py-10">
      <div className="mb-8 text-center">
        <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-orange-100 text-orange-600">
          <Globe2 className="h-7 w-7" />
        </div>
        <h1 className="text-3xl font-bold tracking-tight">Add your brand — zero prompts</h1>
        <p className="mx-auto mt-2 max-w-lg text-stone-600">
          Drop in your website or describe your business in one line. We&apos;ll extract your
          brand identity, tone and top services automatically.
        </p>
      </div>

      {state.step === "input" && (
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <Label htmlFor="biz-input" className="text-sm font-medium">
            Website URL or business description
          </Label>
          <div className="mt-2 flex flex-col gap-2 sm:flex-row">
            <Input
              id="biz-input"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && extract()}
              placeholder={'e.g. https://rosabakery.com  or  "Downtown barbershop, walk-ins welcome"'}
              className="h-12 flex-1"
            />
            <Button onClick={() => extract()} disabled={state.step === "loading"} className="h-12 bg-orange-600 px-6 hover:bg-orange-700">
              <Sparkles className="mr-2 h-4 w-4" /> Analyze
            </Button>
          </div>
          <div className="mt-3 flex flex-wrap items-center gap-2">
            <span className="text-xs text-stone-500">Try:</span>
            {EXAMPLES.map((ex) => (
              <button
                key={ex}
                onClick={() => { setInput(ex); extract(ex); }}
                className="rounded-full border border-stone-200 bg-stone-50 px-3 py-1 text-xs text-stone-600 transition-colors hover:border-orange-300 hover:text-orange-700"
              >
                {ex}
              </button>
            ))}
          </div>
          {error && <p className="mt-3 text-sm font-medium text-red-600">{error}</p>}
        </div>
      )}

      {state.step === "loading" && (
        <div className="rounded-2xl border border-stone-200 bg-white p-6 shadow-sm">
          <div className="mb-5 flex items-center gap-3 text-sm font-medium text-stone-700">
            <Loader2 className="h-4 w-4 animate-spin text-orange-600" />
            Scanning your brand — extracting identity, colors, tone and services…
          </div>
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <Skeleton className="h-12 w-12 rounded-xl" />
              <div className="space-y-2">
                <Skeleton className="h-4 w-40" />
                <Skeleton className="h-3 w-64" />
              </div>
            </div>
            <Skeleton className="h-4 w-full" />
            <Skeleton className="h-4 w-5/6" />
            <div className="flex gap-2">
              <Skeleton className="h-6 w-24 rounded-full" />
              <Skeleton className="h-6 w-28 rounded-full" />
              <Skeleton className="h-6 w-20 rounded-full" />
            </div>
          </div>
        </div>
      )}

      {state.step === "review" && state.brand && (
        <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-stone-50 px-6 py-3">
            <Badge variant="outline" className="gap-1 border-emerald-300 bg-emerald-50 text-emerald-700">
              <Check className="h-3 w-3" /> Brand detected via {state.detectedVia === "url" ? "website" : "description"}
            </Badge>
            <button onClick={() => setState({ step: "input", detectedVia: null, brand: null })} className="text-xs font-medium text-stone-500 hover:text-stone-800">
              ← Start over
            </button>
          </div>
          <div className="p-6">
            <div className="flex items-start gap-4">
              <div
                className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl text-lg font-bold text-white"
                style={{ background: `linear-gradient(135deg, ${state.brand.primaryColor}, ${state.brand.secondaryColor})` }}
              >
                {state.brand.logoText}
              </div>
              {editing ? (
                <div className="flex-1 space-y-3">
                  <div>
                    <Label className="text-xs">Brand name</Label>
                    <Input value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} className="mt-1" />
                  </div>
                  <div>
                    <Label className="text-xs">One-line description</Label>
                    <Input value={draft.description} onChange={(e) => setDraft({ ...draft, description: e.target.value })} className="mt-1" />
                  </div>
                  <div>
                    <Label className="text-xs">Tone of voice</Label>
                    <Input value={draft.tone} onChange={(e) => setDraft({ ...draft, tone: e.target.value })} className="mt-1" />
                  </div>
                  <div>
                    <Label className="text-xs">Target audience</Label>
                    <Input value={draft.audience} onChange={(e) => setDraft({ ...draft, audience: e.target.value })} className="mt-1" />
                  </div>
                  <div>
                    <Label className="text-xs">Top services (one per line)</Label>
                    <Textarea value={draft.services} onChange={(e) => setDraft({ ...draft, services: e.target.value })} rows={4} className="mt-1" />
                  </div>
                  <Button size="sm" onClick={() => setEditing(false)} className="bg-stone-900 hover:bg-stone-800">
                    Done editing
                  </Button>
                </div>
              ) : (
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <h2 className="text-xl font-bold">{draft.name}</h2>
                    <button onClick={() => setEditing(true)} className="ml-auto flex items-center gap-1 rounded-md border border-stone-200 px-2 py-1 text-xs text-stone-600 hover:border-orange-300 hover:text-orange-700">
                      <Pencil className="h-3 w-3" /> Edit
                    </button>
                  </div>
                  <p className="mt-1 text-sm text-stone-600">{draft.description}</p>
                  <div className="mt-4 grid gap-3 text-sm sm:grid-cols-2">
                    <div className="rounded-lg bg-stone-50 p-3">
                      <p className="text-xs font-medium uppercase tracking-wide text-stone-400">Tone</p>
                      <p className="mt-0.5 text-stone-800">{draft.tone}</p>
                    </div>
                    <div className="rounded-lg bg-stone-50 p-3">
                      <p className="text-xs font-medium uppercase tracking-wide text-stone-400">Audience</p>
                      <p className="mt-0.5 text-stone-800">{draft.audience || "—"}</p>
                    </div>
                  </div>
                  <div className="mt-3">
                    <p className="text-xs font-medium uppercase tracking-wide text-stone-400">Top services</p>
                    <ScrollArea className="mt-1 max-h-36">
                      <ul className="space-y-1">
                        {draft.services.split("\n").filter(Boolean).map((s, i) => (
                          <li key={i} className="flex items-center gap-2 text-sm text-stone-700">
                            <Check className="h-3.5 w-3.5 text-orange-600" /> {s}
                          </li>
                        ))}
                      </ul>
                    </ScrollArea>
                  </div>
                </div>
              )}
            </div>
            {error && <p className="mt-3 text-sm font-medium text-red-600">{error}</p>}
            <Button onClick={save} disabled={saving} className="mt-6 w-full h-11 bg-orange-600 text-base hover:bg-orange-700">
              {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Store className="mr-2 h-4 w-4" />}
              Save brand & open Studio <ArrowRight className="ml-1 h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {hasBrands && (
        <div className="mt-6 text-center">
          <button onClick={onSkip} className="text-sm font-medium text-stone-500 underline-offset-4 hover:text-stone-800 hover:underline">
            Skip — go to my existing brands
          </button>
        </div>
      )}
    </div>
  );
}
