"use client";

import { FormEvent, useMemo, useState } from "react";
import {
  PageHeader,
  StatCard,
  Panel,
  AdminButton,
  StatusBadge,
  FilterBar,
  SearchInput,
  SelectFilter,
  EmptyState,
} from "@/components/admin/ui";
import { formatCurrency } from "@/components/admin/adminNav";

type CouponType = "percentage" | "fixed" | "free_shipping" | "bogo";

type Coupon = {
  id: string;
  code: string;
  type: CouponType;
  value: number;
  minOrder: number;
  maxDiscount: number;
  categorySpecific: string;
  productSpecific: string;
  customerSpecific: string;
  expiry: string;
  usageLimit: number;
  used: number;
  status: "Active" | "Expired" | "Disabled";
};

const inputClass =
  "w-full rounded-lg border border-border bg-white px-3 py-2 text-sm outline-none focus:border-accent";

const emptyForm = {
  code: "",
  type: "percentage" as CouponType,
  value: 10,
  minOrder: 5000,
  maxDiscount: 10000,
  categorySpecific: "",
  productSpecific: "",
  customerSpecific: "",
  expiry: "",
  usageLimit: 100,
};

export default function AdminCouponsPage() {
  const [coupons, setCoupons] = useState<Coupon[]>([
    { id: "CPN-1", code: "GNS10", type: "percentage", value: 10, minOrder: 10000, maxDiscount: 15000, categorySpecific: "", productSpecific: "", customerSpecific: "", expiry: "2026-12-31", usageLimit: 500, used: 86, status: "Active" },
    { id: "CPN-2", code: "FLAT5000", type: "fixed", value: 5000, minOrder: 50000, maxDiscount: 5000, categorySpecific: "Refrigerators", productSpecific: "", customerSpecific: "", expiry: "2026-09-30", usageLimit: 200, used: 41, status: "Active" },
    { id: "CPN-3", code: "FREESHIP", type: "free_shipping", value: 0, minOrder: 75000, maxDiscount: 0, categorySpecific: "", productSpecific: "", customerSpecific: "", expiry: "2026-08-31", usageLimit: 1000, used: 220, status: "Active" },
    { id: "CPN-4", code: "BOGO-FAN", type: "bogo", value: 1, minOrder: 0, maxDiscount: 0, categorySpecific: "Fans", productSpecific: "", customerSpecific: "", expiry: "2026-07-15", usageLimit: 50, used: 50, status: "Expired" },
  ]);
  const [form, setForm] = useState(emptyForm);
  const [search, setSearch] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");

  const filtered = useMemo(() => {
    return coupons.filter((c) => {
      const q = search.toLowerCase();
      const matchesSearch = !q || c.code.toLowerCase().includes(q);
      const matchesType = typeFilter === "all" || c.type === typeFilter;
      return matchesSearch && matchesType;
    });
  }, [coupons, search, typeFilter]);

  const handleCreate = (e: FormEvent) => {
    e.preventDefault();
    if (!form.code.trim()) return;
    const next: Coupon = {
      id: `CPN-${Date.now()}`,
      code: form.code.trim().toUpperCase(),
      type: form.type,
      value: form.value,
      minOrder: form.minOrder,
      maxDiscount: form.maxDiscount,
      categorySpecific: form.categorySpecific,
      productSpecific: form.productSpecific,
      customerSpecific: form.customerSpecific,
      expiry: form.expiry || "2026-12-31",
      usageLimit: form.usageLimit,
      used: 0,
      status: "Active",
    };
    setCoupons((prev) => [next, ...prev]);
    setForm(emptyForm);
  };

  const typeLabel = (type: CouponType) => {
    if (type === "percentage") return "Percentage";
    if (type === "fixed") return "Fixed";
    if (type === "free_shipping") return "Free Shipping";
    return "BOGO";
  };

  const valueLabel = (c: Coupon) => {
    if (c.type === "percentage") return `${c.value}%`;
    if (c.type === "fixed") return formatCurrency(c.value);
    if (c.type === "free_shipping") return "Free shipping";
    return `Buy ${c.value} Get 1`;
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Coupons"
        description="Create and manage percentage, fixed, free shipping, and BOGO promotions."
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Total Coupons" value={coupons.length} />
        <StatCard label="Active" value={coupons.filter((c) => c.status === "Active").length} tone="success" />
        <StatCard label="Expired" value={coupons.filter((c) => c.status === "Expired").length} tone="warning" />
        <StatCard label="Total Redemptions" value={coupons.reduce((s, c) => s + c.used, 0)} tone="info" />
      </div>

      <div className="grid gap-4 xl:grid-cols-3">
        <Panel title="Create Coupon" className="xl:col-span-1">
          <form onSubmit={handleCreate} className="space-y-3">
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Code</label>
              <input className={inputClass} value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} required />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Type</label>
              <select className={inputClass} value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value as CouponType })}>
                <option value="percentage">Percentage</option>
                <option value="fixed">Fixed amount</option>
                <option value="free_shipping">Free shipping</option>
                <option value="bogo">BOGO</option>
              </select>
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Value</label>
              <input type="number" className={inputClass} value={form.value} onChange={(e) => setForm({ ...form, value: Number(e.target.value) })} />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Min Order</label>
              <input type="number" className={inputClass} value={form.minOrder} onChange={(e) => setForm({ ...form, minOrder: Number(e.target.value) })} />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Max Discount</label>
              <input type="number" className={inputClass} value={form.maxDiscount} onChange={(e) => setForm({ ...form, maxDiscount: Number(e.target.value) })} />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Category Specific</label>
              <input className={inputClass} value={form.categorySpecific} onChange={(e) => setForm({ ...form, categorySpecific: e.target.value })} placeholder="Optional" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Product Specific</label>
              <input className={inputClass} value={form.productSpecific} onChange={(e) => setForm({ ...form, productSpecific: e.target.value })} placeholder="Optional" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Customer Specific</label>
              <input className={inputClass} value={form.customerSpecific} onChange={(e) => setForm({ ...form, customerSpecific: e.target.value })} placeholder="Optional email/ID" />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Expiry</label>
              <input type="date" className={inputClass} value={form.expiry} onChange={(e) => setForm({ ...form, expiry: e.target.value })} />
            </div>
            <div>
              <label className="mb-1 block text-xs font-semibold text-muted-foreground">Usage Limit</label>
              <input type="number" className={inputClass} value={form.usageLimit} onChange={(e) => setForm({ ...form, usageLimit: Number(e.target.value) })} />
            </div>
            <AdminButton type="submit">Create Coupon</AdminButton>
          </form>
        </Panel>

        <Panel title="Coupon List" className="xl:col-span-2">
          <FilterBar>
            <SearchInput value={search} onChange={setSearch} placeholder="Search code…" />
            <SelectFilter
              value={typeFilter}
              onChange={setTypeFilter}
              options={[
                { value: "all", label: "All types" },
                { value: "percentage", label: "Percentage" },
                { value: "fixed", label: "Fixed" },
                { value: "free_shipping", label: "Free shipping" },
                { value: "bogo", label: "BOGO" },
              ]}
            />
          </FilterBar>

          {filtered.length === 0 ? (
            <EmptyState title="No coupons found" description="Create a coupon or adjust filters." />
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[720px] text-left text-sm">
                <thead>
                  <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                    <th className="pb-2 font-semibold">Code</th>
                    <th className="pb-2 font-semibold">Type</th>
                    <th className="pb-2 font-semibold">Value</th>
                    <th className="pb-2 font-semibold">Conditions</th>
                    <th className="pb-2 font-semibold">Usage</th>
                    <th className="pb-2 font-semibold">Status</th>
                    <th className="pb-2 font-semibold">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filtered.map((coupon) => (
                    <tr key={coupon.id} className="border-b border-border/60 align-top">
                      <td className="py-3 font-semibold">{coupon.code}</td>
                      <td className="py-3">{typeLabel(coupon.type)}</td>
                      <td className="py-3">{valueLabel(coupon)}</td>
                      <td className="py-3 text-xs text-muted-foreground">
                        <div>Min {formatCurrency(coupon.minOrder)}</div>
                        {coupon.maxDiscount ? <div>Max disc {formatCurrency(coupon.maxDiscount)}</div> : null}
                        {coupon.categorySpecific ? <div>Cat: {coupon.categorySpecific}</div> : null}
                        {coupon.productSpecific ? <div>Prod: {coupon.productSpecific}</div> : null}
                        {coupon.customerSpecific ? <div>Cust: {coupon.customerSpecific}</div> : null}
                        <div>Exp: {coupon.expiry}</div>
                      </td>
                      <td className="py-3">{coupon.used}/{coupon.usageLimit}</td>
                      <td className="py-3"><StatusBadge status={coupon.status} /></td>
                      <td className="py-3">
                        <div className="flex flex-wrap gap-1.5">
                          <AdminButton
                            variant="secondary"
                            onClick={() =>
                              setCoupons((prev) =>
                                prev.map((c) =>
                                  c.id === coupon.id
                                    ? { ...c, status: c.status === "Active" ? "Disabled" : "Active" }
                                    : c,
                                ),
                              )
                            }
                          >
                            {coupon.status === "Active" ? "Disable" : "Enable"}
                          </AdminButton>
                          <AdminButton
                            variant="danger"
                            onClick={() => setCoupons((prev) => prev.filter((c) => c.id !== coupon.id))}
                          >
                            Delete
                          </AdminButton>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </Panel>
      </div>
    </div>
  );
}
