"use client";

/**
 * Website Upload page  (/website-upload)
 * ---------------------------------------
 * Lets the user enter brand details and create a new brand.
 * Creates the brand via API, triggers technical audit + profile extraction.
 */

import { useState } from "react";
import { Globe, MapPin, Briefcase, Tag, FileUp, FileText, BookOpen, X, Sparkles, CheckCircle2, ArrowRight, Loader2, Building2, Search, ChevronDown } from "lucide-react";
import IndustrySearch from "@/components/industry-search";
import { ChipsInput } from "@/components/ui/chips-input";
import Link from "next/link";
import { useBrand } from "@/context/brand-context";
import { useBackgroundTasks } from "@/lib/stores/task-store";

// ─── Types ─────────────────────────────────────────────────────────────────

interface EnrichmentFile {
  id:       string;
  file:     File;
  name:     string;
  type:     "Document" | "Whitepaper" | "PDF";
  sizeText: string;
  status?:  "uploading" | "ready" | "failed";
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

// ─── Page component ───────────────────────────────────────────────────────────

export default function WebsiteUploadPage() {
  const [brandName,        setBrandName]        = useState("");
  const [url,              setUrl]              = useState("");
  const [industry,         setIndustry]         = useState("");
  const [industryCategory, setIndustryCategory] = useState("");
  const [locations,        setLocations]        = useState<string[]>([]);
  const [primaryServices,  setPrimaryServices]  = useState<string[]>([]);
  const [secondaryServices,setSecondaryServices]= useState<string[]>([]);
  const [showSecondary,    setShowSecondary]    = useState(false);
  const [loading,          setLoading]          = useState(false);
  const [analyzed,         setAnalyzed]         = useState(false);
  const [uploadedFiles, setUploadedFiles] = useState<EnrichmentFile[]>([]);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [setupDone,   setSetupDone]   = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const { brand, brands, orgId, refresh: refreshBrands } = useBrand();
  const { addTask, completeTask } = useBackgroundTasks();

  const canSubmit = brandName.trim() && url.trim() && industry.trim().length > 0 && locations.length > 0 && primaryServices.length > 0;

  // Upload file to the real backend API
  async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>, type: EnrichmentFile["type"]) {
    setUploadError(null);
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = "";

    const MAX_BYTES = 10 * 1024 * 1024;
    if (file.size > MAX_BYTES) { setUploadError(`${file.name} is too large. Max 10 MB.`); return; }

    // Optimistic UI: add to list immediately
    const tempId = `temp_${Date.now()}`;
    const entry: EnrichmentFile = { id: tempId, file, name: file.name, type, sizeText: formatFileSize(file.size), status: "uploading" };
    setUploadedFiles(prev => [...prev, entry]);

    // Determine which brand to upload to
    const targetBrandId = brand.id || brands[0]?.id;
    if (!targetBrandId) { setUploadError("Create a brand first before uploading files."); setUploadedFiles(prev => prev.filter(f => f.id !== tempId)); return; }

    try {
      const fd = new FormData();
      fd.append("file", file);
      fd.append("fileType", type.toLowerCase());
      const res = await fetch(`/api/brands/${targetBrandId}/enrichment-files`, { method: "POST", body: fd });
      if (!res.ok) { const d = await res.json().catch(() => ({})); throw new Error(d.error || "Upload failed"); }
      const data = await res.json();
      setUploadedFiles(prev => prev.map(f => f.id === tempId ? { ...f, id: data.file.id, status: "ready" } : f));
    } catch (err) {
      setUploadError(err instanceof Error ? err.message : "Upload failed");
      setUploadedFiles(prev => prev.filter(f => f.id !== tempId));
    }
  }

  async function removeFile(id: string) {
    const targetBrandId = brand.id || brands[0]?.id;
    if (targetBrandId && !id.startsWith("temp_")) {
      fetch(`/api/brands/${targetBrandId}/enrichment-files/${id}`, { method: "DELETE" }).catch(() => {});
    }
    setUploadedFiles(prev => prev.filter(f => f.id !== id));
  }

  async function handleAnalyze() {
    if (!canSubmit) return;
    setAnalyzed(false);
    setSubmitError(null);
    setLoading(true);

    try {
      if (!orgId) {
        setSubmitError("No organization found. Complete onboarding first.");
        setLoading(false);
        return;
      }

      // Create the brand via the real API
      const res = await fetch("/api/brands", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          orgId,
          name: brandName.trim(),
          domain: url.trim(),
          industry: industry !== "Select industry..." ? industry : undefined,
          locations,
          primaryServices,
          secondaryServices,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        setSubmitError(data.error || "Failed to create brand");
        setLoading(false);
        return;
      }

      const brandData = await res.json();

      // Trigger brand identity extraction + technical audit in the background
      if (brandData?.id) {
        const auditTaskId = addTask({ id: `setup_audit_${Date.now()}`, type: "technical_audit", label: "Running Initial Technical Audit...", brandId: brandData.id, resultUrl: "/technical-audit" });
        fetch("/api/brands/extract", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ brandId: brandData.id, domain: url.trim() }),
        }).catch(() => {});

        fetch("/api/technical-audit/run", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ brandId: brandData.id }),
        }).then(() => completeTask(auditTaskId, { resultUrl: "/technical-audit", resultSummary: "Initial audit complete" })).catch(() => {});
      }

      // Refresh the brand switcher so the new brand appears immediately
      await refreshBrands();

      setLoading(false);
      setAnalyzed(true);
    } catch {
      setSubmitError("Network error — please try again");
      setLoading(false);
    }
  }

  return (
    <div className="space-y-6 max-w-4xl">

      {/* ── 1. Heading ── */}
      <div>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
            <Globe className="w-5 h-5 text-brand-600" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-slate-900">AI Website Intake &amp; Setup</h1>
            <p className="text-slate-500 text-sm mt-0.5">
              Add a new brand to meSEO. Fill in the details below to run an instant audit for <span className="font-semibold text-slate-700">{brand.name}</span>.
            </p>
          </div>
        </div>
      </div>

      {/* ── 2. Intake form ── */}
      <div className="bg-white rounded-xl border border-slate-200 p-6 space-y-5">
        <div className="flex items-center gap-2 mb-1">
          <Briefcase className="w-4 h-4 text-brand-600" />
          <p className="text-sm font-bold text-slate-800">Brand Details</p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {/* Brand Name */}
          <div>
            <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 mb-1.5">
              <Building2 className="w-3 h-3 text-slate-400" /> Brand Name
            </label>
            <input
              type="text"
              placeholder="e.g. Acme Corp"
              value={brandName}
              onChange={(e) => setBrandName(e.target.value)}
              className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

          {/* Website URL */}
          <div>
            <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 mb-1.5">
              <Globe className="w-3 h-3 text-slate-400" /> Website URL
            </label>
            <input
              type="url"
              placeholder={`https://${brand.domain}`}
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              className="w-full rounded-lg border border-slate-200 px-4 py-2.5 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent transition"
            />
          </div>

          {/* Industry */}
          <div>
            <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 mb-1.5">
              <Tag className="w-3 h-3 text-slate-400" /> Industry
            </label>
            <IndustrySearch value={industry} onChange={(ind, cat) => { setIndustry(ind); setIndustryCategory(cat); }} />
          </div>

          {/* Primary Services */}
          <div>
            <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 mb-1.5">
              <Briefcase className="w-3 h-3 text-slate-400" /> Primary Services
              <span className="text-slate-400 font-normal ml-1">· top 1–3</span>
            </label>
            <ChipsInput
              value={primaryServices}
              onChange={setPrimaryServices}
              placeholder="e.g. Lawn Care, Fertilization"
              maxItems={5}
            />
          </div>

          {/* Locations */}
          <div>
            <label className="flex items-center gap-1.5 text-xs font-semibold text-slate-600 mb-1.5">
              <MapPin className="w-3 h-3 text-slate-400" /> Locations
            </label>
            <ChipsInput
              value={locations}
              onChange={setLocations}
              placeholder="e.g. Atlanta, GA"
            />
          </div>

          {/* Secondary Services — collapsible */}
          <div className="sm:col-span-2">
            <button
              type="button"
              onClick={() => setShowSecondary((s) => !s)}
              className="flex items-center gap-1 text-xs font-semibold text-brand-600 hover:text-brand-700 transition-colors mb-1.5"
            >
              <ChevronDown className={`w-3 h-3 transition-transform ${showSecondary ? "rotate-180" : ""}`} />
              {showSecondary ? "Hide" : "Add"} secondary services
              {secondaryServices.length > 0 && !showSecondary && (
                <span className="ml-1 text-slate-400 font-normal">({secondaryServices.length})</span>
              )}
            </button>
            {showSecondary && (
              <ChipsInput
                value={secondaryServices}
                onChange={setSecondaryServices}
                placeholder="e.g. Weed Control, Aeration, Overseeding"
                maxItems={20}
              />
            )}
          </div>
        </div>

        {/* Error message */}
        {submitError && (
          <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 text-sm text-red-700">
            {submitError}
          </div>
        )}

        {/* Submit */}
        <div className="flex items-center gap-3 pt-2">
          <button
            onClick={handleAnalyze}
            disabled={loading || !canSubmit}
            className="flex items-center gap-2 px-6 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors shadow-sm"
          >
            <Search className="w-4 h-4" />
            {loading ? "Analyzing…" : "Create Brand & Run AI Setup"}
          </button>
          {!canSubmit && (brandName.trim() || url.trim()) && (
            <p className="text-[11px] text-slate-400">Fill in Brand Name, URL, Industry, at least one Location, and at least one Primary Service to continue</p>
          )}
        </div>
      </div>

      {/* ── 3. Data Enrichment ── */}
      <div className="bg-white rounded-xl border border-slate-200 p-6 space-y-4">
        <div className="flex items-center gap-2">
          <FileUp className="w-4 h-4 text-brand-600" />
          <p className="text-sm font-bold text-slate-800">Data Enrichment</p>
          <span className="ml-auto text-[10px] font-semibold text-slate-400 bg-slate-50 border border-slate-200 rounded-full px-2 py-0.5">Optional</span>
        </div>
        <p className="text-xs text-slate-500">
          Upload documents, whitepapers, and PDFs to enrich AI insights and content generation. Uploaded files are processed and their content is used to make AI analysis more specific to your brand.
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {/* Documents */}
          <label className="group flex flex-col items-center gap-2 px-4 py-6 rounded-xl border-2 border-dashed border-slate-200 hover:border-brand-300 hover:bg-brand-50/30 transition-colors cursor-pointer">
            <FileText className="w-6 h-6 text-slate-400 group-hover:text-brand-500 transition-colors" />
            <span className="text-xs font-semibold text-slate-600 group-hover:text-brand-700">Documents</span>
            <span className="text-[10px] text-slate-400">.doc, .docx, .txt</span>
            <input type="file" accept=".doc,.docx,.txt" className="hidden" onChange={(e) => handleFileSelect(e, "Document")} />
          </label>

          {/* Whitepapers */}
          <label className="group flex flex-col items-center gap-2 px-4 py-6 rounded-xl border-2 border-dashed border-slate-200 hover:border-brand-300 hover:bg-brand-50/30 transition-colors cursor-pointer">
            <BookOpen className="w-6 h-6 text-slate-400 group-hover:text-brand-500 transition-colors" />
            <span className="text-xs font-semibold text-slate-600 group-hover:text-brand-700">Whitepapers</span>
            <span className="text-[10px] text-slate-400">.pdf, .doc, .docx</span>
            <input type="file" accept=".pdf,.doc,.docx" className="hidden" onChange={(e) => handleFileSelect(e, "Whitepaper")} />
          </label>

          {/* PDFs */}
          <label className="group flex flex-col items-center gap-2 px-4 py-6 rounded-xl border-2 border-dashed border-slate-200 hover:border-brand-300 hover:bg-brand-50/30 transition-colors cursor-pointer">
            <FileUp className="w-6 h-6 text-slate-400 group-hover:text-brand-500 transition-colors" />
            <span className="text-xs font-semibold text-slate-600 group-hover:text-brand-700">PDFs</span>
            <span className="text-[10px] text-slate-400">.pdf</span>
            <input type="file" accept=".pdf" className="hidden" onChange={(e) => handleFileSelect(e, "PDF")} />
          </label>
        </div>

        {/* Upload error */}
        {uploadError && (
          <div className="bg-red-50 border border-red-200 rounded-lg px-3 py-2 text-xs text-red-700">
            {uploadError}
          </div>
        )}

        {/* Real selected files list */}
        {uploadedFiles.length > 0 && (
          <div className="space-y-2 pt-2">
            <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400">
              Selected files ({uploadedFiles.length})
            </p>
            {uploadedFiles.map((f) => (
              <div key={f.id} className="flex items-center gap-3 px-3 py-2 rounded-lg bg-slate-50 border border-slate-100">
                {f.status === "uploading" ? <Loader2 className="w-3.5 h-3.5 text-brand-500 animate-spin shrink-0" /> : <FileText className="w-3.5 h-3.5 text-brand-500 shrink-0" />}
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-semibold text-slate-700 truncate">{f.name}</p>
                  <p className="text-[10px] text-slate-400">{f.type} · {f.sizeText}{f.status === "uploading" ? " · Uploading..." : f.status === "ready" ? " · Ready" : ""}</p>
                </div>
                {f.status !== "uploading" && (
                  <button onClick={() => removeFile(f.id)} className="shrink-0 w-5 h-5 rounded flex items-center justify-center text-slate-400 hover:text-red-500 hover:bg-red-50 transition-colors" title="Remove file">
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── 4. Loading spinner ── */}
      {loading && (
        <div className="bg-white rounded-xl border border-slate-200 p-12 flex flex-col items-center gap-4 text-slate-500">
          <div className="w-10 h-10 border-4 border-brand-100 border-t-brand-600 rounded-full animate-spin" />
          <p className="text-sm font-medium">Scanning your website…</p>
          <p className="text-xs text-slate-400">This usually takes a few seconds</p>
        </div>
      )}

      {/* ── 5. Results ── */}
      {analyzed && !loading && (
        <div className="space-y-5">

          {/* 5a. Brand created + audits running */}
          <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
            <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2 bg-brand-50/60">
              <Sparkles className="w-4 h-4 text-brand-600" />
              <h2 className="font-bold text-slate-800 text-sm">Brand Created</h2>
              <span className="ml-auto text-[10px] font-semibold text-green-600 bg-green-100 border border-green-200 rounded-full px-2 py-0.5">Success</span>
            </div>
            <div className="px-5 py-6">
              <div className="flex items-start gap-4">
                <div className="w-10 h-10 rounded-xl bg-green-50 border border-green-200 flex items-center justify-center shrink-0">
                  <CheckCircle2 className="w-5 h-5 text-green-600" />
                </div>
                <div>
                  <p className="text-sm font-bold text-slate-900">{brandName || url} has been added to your workspace</p>
                  <p className="text-xs text-slate-500 mt-1 leading-relaxed">
                    A technical audit and brand profile extraction are running in the background. Results will appear on the Dashboard and Technical Audit pages once complete.
                  </p>
                  <div className="flex items-center gap-3 mt-3">
                    <span className="flex items-center gap-1.5 text-[11px] font-semibold text-blue-600 bg-blue-50 border border-blue-200 px-2.5 py-1 rounded-lg">
                      <Loader2 className="w-3 h-3 animate-spin" /> Technical audit running
                    </span>
                    <span className="flex items-center gap-1.5 text-[11px] font-semibold text-violet-600 bg-violet-50 border border-violet-200 px-2.5 py-1 rounded-lg">
                      <Loader2 className="w-3 h-3 animate-spin" /> Brand profile extracting
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* 5b. Next steps */}
          {!setupDone ? (
            <div className="bg-white rounded-xl border border-slate-200 p-6 space-y-4">
              <div className="flex items-center gap-2">
                <Sparkles className="w-4 h-4 text-brand-600" />
                <p className="text-sm font-bold text-slate-800">Ready to Complete Setup</p>
              </div>
              <p className="text-xs text-slate-500 leading-relaxed">
                After setup, this brand will be added to <span className="font-semibold text-slate-700">Brands Hub</span> and data will populate across the entire platform — including Dashboard, AI Strategist, Execution Hub, and Report Studio.
              </p>
              <div className="flex items-center gap-4 pt-1">
                <button
                  onClick={() => setSetupDone(true)}
                  className="flex items-center gap-2 px-6 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-semibold hover:bg-brand-700 transition-colors shadow-sm"
                >
                  <CheckCircle2 className="w-4 h-4" />
                  Complete Setup
                </button>
                <div className="flex items-center gap-3 text-[11px] text-slate-400">
                  <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-slate-300" /> Added to Brands Hub</span>
                  <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-slate-300" /> Data syncs platform-wide</span>
                  <span className="flex items-center gap-1"><CheckCircle2 className="w-3 h-3 text-slate-300" /> AI insights activated</span>
                </div>
              </div>
            </div>
          ) : (
            <div className="bg-gradient-to-r from-emerald-50 to-green-50 rounded-xl border border-emerald-200 p-6 space-y-4">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center">
                  <CheckCircle2 className="w-5 h-5 text-emerald-600" />
                </div>
                <div>
                  <p className="text-sm font-bold text-emerald-900">Brand Setup Complete</p>
                  <p className="text-xs text-emerald-700 mt-0.5">
                    <span className="font-semibold">{brandName || "New Brand"}</span> has been added to your workspace. Data is now populating across all modules.
                  </p>
                </div>
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                {[
                  { label: "Brands Hub",      status: "Brand added",     href: "/brands-hub" },
                  { label: "Dashboard",        status: "Data syncing",    href: "/dashboard" },
                  { label: "AI Strategist",    status: "Insights ready",  href: "/ai-strategist" },
                  { label: "Execution Hub",    status: "Tasks generated", href: "/execution-hub" },
                ].map((item) => (
                  <Link key={item.label} href={item.href}
                    className="flex items-center gap-2.5 px-3 py-2.5 rounded-lg bg-white border border-emerald-200 hover:border-emerald-300 hover:shadow-sm transition-all group">
                    <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 shrink-0" />
                    <div className="min-w-0">
                      <p className="text-xs font-semibold text-slate-700 group-hover:text-brand-600 transition-colors">{item.label}</p>
                      <p className="text-[10px] text-emerald-600">{item.status}</p>
                    </div>
                    <ArrowRight className="w-3 h-3 text-slate-300 group-hover:text-brand-500 ml-auto shrink-0 transition-colors" />
                  </Link>
                ))}
              </div>
            </div>
          )}

        </div>
      )}

      {/* ── 6. Existing brands ── */}
      {brands.length > 0 && (
      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
        <div className="px-5 py-4 border-b border-slate-100">
          <h2 className="font-semibold text-slate-800">Your Brands</h2>
          <p className="text-xs text-slate-400 mt-0.5">{brands.length} brand{brands.length !== 1 ? "s" : ""} in your workspace</p>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-slate-100 text-xs text-slate-500 uppercase tracking-wide">
                <th className="text-left px-5 py-3 font-medium">Brand</th>
                <th className="text-left px-3 py-3 font-medium">Domain</th>
              </tr>
            </thead>
            <tbody>
              {brands.map((b, i) => (
                <tr
                  key={b.id}
                  className={`hover:bg-slate-50 transition-colors ${
                    i < brands.length - 1 ? "border-b border-slate-50" : ""
                  }`}
                >
                  <td className="px-5 py-3 font-medium text-slate-800">{b.name}</td>
                  <td className="px-3 py-3 text-slate-500">{b.domain}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
      )}

    </div>
  );
}
