"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Building2, MapPin, Briefcase, ChevronDown, Loader2, CheckCircle2, ArrowLeft } from "lucide-react";
import { ChipsInput } from "@/components/ui/chips-input";
import { useBrand } from "@/context/brand-context";
import { getBrandLocations, getBrandServices } from "@/lib/brand-helpers";

interface BrandData {
  id: string;
  name: string;
  domain: string;
  industry: string | null;
  location: string | null;
  serviceType: string | null;
  locations: string[];
  primaryServices: string[];
  secondaryServices: string[];
}

export default function EditBrandPage() {
  const params = useParams<{ brandId: string }>();
  const brandId = params.brandId;
  const router = useRouter();
  const { orgId } = useBrand();

  const [brand, setBrand] = useState<BrandData | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [name, setName] = useState("");
  const [locations, setLocations] = useState<string[]>([]);
  const [primaryServices, setPrimaryServices] = useState<string[]>([]);
  const [secondaryServices, setSecondaryServices] = useState<string[]>([]);
  const [showSecondary, setShowSecondary] = useState(false);

  useEffect(() => {
    if (!orgId || !brandId) return;
    setLoading(true);
    fetch(`/api/brands?orgId=${encodeURIComponent(orgId)}`, { cache: "no-store" })
      .then((r) => r.json())
      .then((all: BrandData[]) => {
        const found = Array.isArray(all) ? all.find((b) => b.id === brandId) : null;
        if (!found) { setError("Brand not found."); setLoading(false); return; }
        setBrand(found);
        setName(found.name);
        setLocations(
          getBrandLocations(found),
        );
        const services = getBrandServices(found);
        setPrimaryServices(services.primary);
        const secondary = services.secondary;
        setSecondaryServices(secondary);
        if (secondary.length > 0) setShowSecondary(true);
        setLoading(false);
      })
      .catch(() => { setError("Failed to load brand."); setLoading(false); });
  }, [orgId, brandId]);

  async function handleSave() {
    if (!brandId || !name.trim() || locations.length === 0 || primaryServices.length === 0) return;
    setSaving(true);
    setError(null);
    try {
      const res = await fetch(`/api/brands/${brandId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), locations, primaryServices, secondaryServices }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error || `Save failed (HTTP ${res.status})`);
      }
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Save failed");
    } finally {
      setSaving(false);
    }
  }

  const canSave = name.trim() && locations.length > 0 && primaryServices.length > 0;

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-6 h-6 text-brand-500 animate-spin" />
      </div>
    );
  }

  if (error && !brand) {
    return (
      <div className="max-w-2xl space-y-4">
        <p className="text-sm text-red-600">{error}</p>
        <button onClick={() => router.back()} className="text-sm text-brand-600 hover:underline">← Back</button>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-2xl">
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.back()}
          className="p-2 rounded-lg hover:bg-slate-100 transition-colors text-slate-500"
          aria-label="Go back"
        >
          <ArrowLeft className="w-4 h-4" />
        </button>
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Edit Brand</h1>
          <p className="text-slate-500 text-sm mt-0.5">{brand?.domain}</p>
        </div>
      </div>

      <div className="bg-white rounded-xl border border-slate-200 p-6 space-y-5">
        <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"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="e.g. Acme Corp"
            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>

        <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>

        <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>

        <div>
          <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" : "Edit"} 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>

        {(!locations.length || !primaryServices.length) && (
          <p className="text-xs text-amber-600">
            At least one location and one primary service are required.
          </p>
        )}

        {error && <p className="text-xs text-red-600">{error}</p>}
      </div>

      <div className="flex items-center gap-3">
        <button
          onClick={handleSave}
          disabled={!canSave || saving}
          className="flex items-center gap-2 px-5 py-2.5 bg-brand-600 text-white text-sm font-semibold rounded-xl hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          {saving ? (
            <Loader2 className="w-4 h-4 animate-spin" />
          ) : saved ? (
            <CheckCircle2 className="w-4 h-4" />
          ) : null}
          {saving ? "Saving…" : saved ? "Saved!" : "Save Changes"}
        </button>
        <button
          onClick={() => router.back()}
          className="px-5 py-2.5 text-sm font-semibold text-slate-600 rounded-xl border border-slate-200 hover:bg-slate-50 transition-colors"
        >
          Cancel
        </button>
      </div>
    </div>
  );
}
