"use client";

import { useMemo, useState, type FormEvent } from "react";
import {
  PageHeader,
  Panel,
  AdminButton,
  StatCard,
  StatusBadge,
  FilterBar,
  SearchInput,
  SelectFilter,
  EmptyState,
} from "@/components/admin/ui";
import { Field, FormGrid, TextInput, TextSelect, TextTextarea } from "@/components/admin/formFields";
import { useAuth } from "@/context/AuthContext";
import { useStore } from "@/context/StoreContext";
import { api, ApiError, mediaOrPlaceholder } from "@/lib/api";
import type { BrandRecord } from "@/data/ecommerceStore";

type BrandFormState = {
  id?: string;
  name: string;
  description: string;
  website: string;
  status: "active" | "inactive";
};

const emptyForm = (): BrandFormState => ({
  name: "",
  description: "",
  website: "",
  status: "active",
});

export default function AdminBrandsPage() {
  const { token } = useAuth();
  const { store, refreshStore } = useStore();
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [form, setForm] = useState<BrandFormState>(emptyForm());
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");
  const [showForm, setShowForm] = useState(false);

  const productCounts = useMemo(() => {
    const counts: Record<string, number> = {};
    store.products.forEach((p) => {
      counts[p.brand_id] = (counts[p.brand_id] || 0) + 1;
    });
    return counts;
  }, [store.products]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return store.brands.filter((brand) => {
      // Brand records from the store have no status field yet; treat listed brands as active.
      if (statusFilter === "inactive") return false;
      if (!q) return true;
      return brand.name.toLowerCase().includes(q);
    });
  }, [store.brands, search, statusFilter]);

  const openCreate = () => {
    setForm(emptyForm());
    setLogoFile(null);
    setShowForm(true);
    setError("");
  };

  const openEdit = (brand: BrandRecord) => {
    setForm({
      id: brand.id,
      name: brand.name,
      description: "",
      website: "",
      status: "active",
    });
    setLogoFile(null);
    setShowForm(true);
    setError("");
  };

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!form.name.trim()) {
      setError("Brand name is required.");
      return;
    }
    setBusy(true);
    setError("");
    setMessage("");
    try {
      const fd = new FormData();
      fd.set("name", form.name.trim());
      fd.set("description", form.description.trim());
      fd.set("website", form.website.trim());
      fd.set("status", form.status);
      if (logoFile) fd.set("logo", logoFile);

      if (form.id) {
        await api.admin.updateBrand(form.id, fd, token);
        if (logoFile) {
          const logoFd = new FormData();
          logoFd.set("logo", logoFile);
          await api.admin.uploadBrandLogo(form.id, logoFd, token);
        }
        setMessage("Brand updated.");
      } else {
        await api.admin.createBrand(fd, token);
        setMessage("Brand created.");
      }
      await refreshStore();
      setShowForm(false);
      setForm(emptyForm());
      setLogoFile(null);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Failed to save brand.");
    } finally {
      setBusy(false);
    }
  };

  const deleteBrand = async (brand: BrandRecord) => {
    if (!window.confirm(`Delete brand “${brand.name}”?`)) return;
    setBusy(true);
    setError("");
    try {
      await api.admin.deleteBrand(brand.id, token);
      await refreshStore();
      setMessage("Brand deleted.");
      if (form.id === brand.id) {
        setShowForm(false);
        setForm(emptyForm());
      }
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Failed to delete brand.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Brands"
        description="Manage brand logos, descriptions, and storefront visibility."
        actions={<AdminButton onClick={openCreate}>Add Brand</AdminButton>}
      />

      <div className="grid gap-3 sm:grid-cols-3">
        <StatCard label="Brands" value={store.brands.length} />
        <StatCard
          label="With products"
          value={store.brands.filter((b) => (productCounts[b.id] || 0) > 0).length}
          tone="success"
        />
        <StatCard
          label="Unused"
          value={store.brands.filter((b) => !(productCounts[b.id] || 0)).length}
          tone="warning"
        />
      </div>

      {(message || error) && (
        <div
          className={`rounded-xl border px-4 py-3 text-sm ${
            error
              ? "border-destructive/30 bg-destructive/10 text-destructive"
              : "border-emerald-200 bg-emerald-50 text-emerald-800"
          }`}
        >
          {error || message}
        </div>
      )}

      {showForm ? (
        <Panel
          title={form.id ? "Edit brand" : "Add brand"}
          description="Logo, name, description, website, and status"
          actions={
            <AdminButton
              variant="ghost"
              onClick={() => {
                setShowForm(false);
                setForm(emptyForm());
              }}
            >
              Close
            </AdminButton>
          }
        >
          <form onSubmit={onSubmit} className="space-y-4">
            <FormGrid cols={2}>
              <Field label="Name *">
                <TextInput
                  value={form.name}
                  onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
                  required
                />
              </Field>
              <Field label="Website">
                <TextInput
                  type="url"
                  placeholder="https://"
                  value={form.website}
                  onChange={(e) => setForm((prev) => ({ ...prev, website: e.target.value }))}
                />
              </Field>
              <Field label="Status">
                <TextSelect
                  value={form.status}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      status: e.target.value as "active" | "inactive",
                    }))
                  }
                >
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </TextSelect>
              </Field>
              <Field label="Logo">
                <TextInput
                  type="file"
                  accept="image/*"
                  onChange={(e) => setLogoFile(e.target.files?.[0] || null)}
                />
              </Field>
              <Field label="Description" className="sm:col-span-2">
                <TextTextarea
                  value={form.description}
                  onChange={(e) => setForm((prev) => ({ ...prev, description: e.target.value }))}
                  rows={4}
                />
              </Field>
            </FormGrid>
            <div className="flex gap-2">
              <AdminButton type="submit">{busy ? "Saving…" : form.id ? "Update brand" : "Create brand"}</AdminButton>
              <AdminButton
                variant="secondary"
                onClick={() => {
                  setShowForm(false);
                  setForm(emptyForm());
                }}
              >
                Cancel
              </AdminButton>
            </div>
          </form>
        </Panel>
      ) : null}

      <Panel title="Brand list" description="Search and manage brand records">
        <FilterBar>
          <SearchInput value={search} onChange={setSearch} placeholder="Search brands…" />
          <SelectFilter
            value={statusFilter}
            onChange={setStatusFilter}
            options={[
              { value: "all", label: "All statuses" },
              { value: "active", label: "Active" },
              { value: "inactive", label: "Inactive" },
            ]}
          />
        </FilterBar>

        {filtered.length === 0 ? (
          <EmptyState title="No brands found" description="Add a brand to associate with products." />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[700px] text-left text-sm">
              <thead>
                <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                  <th className="py-2 pr-3">Logo</th>
                  <th className="py-2 pr-3">Name</th>
                  <th className="py-2 pr-3">Products</th>
                  <th className="py-2 pr-3">Status</th>
                  <th className="py-2">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((brand) => (
                  <tr key={brand.id} className="border-b border-border/70">
                    <td className="py-2.5 pr-3">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={mediaOrPlaceholder(brand.logo)}
                        alt=""
                        className="h-10 w-10 rounded-lg object-cover border border-border bg-white"
                      />
                    </td>
                    <td className="py-2.5 pr-3 font-medium">{brand.name}</td>
                    <td className="py-2.5 pr-3">{productCounts[brand.id] || 0}</td>
                    <td className="py-2.5 pr-3">
                      <StatusBadge status="active" />
                    </td>
                    <td className="py-2.5">
                      <div className="flex flex-wrap gap-2">
                        <button
                          type="button"
                          className="text-xs font-semibold text-accent hover:underline"
                          onClick={() => openEdit(brand)}
                        >
                          Edit
                        </button>
                        <button
                          type="button"
                          className="text-xs font-semibold text-destructive hover:underline"
                          onClick={() => void deleteBrand(brand)}
                        >
                          Delete
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <p className="mt-4 text-xs text-muted-foreground">
          Showing {filtered.length} of {store.brands.length} brands
        </p>
      </Panel>
    </div>
  );
}
