"use client";

import { 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 Customer = {
  id: string;
  name: string;
  email: string;
  phone: string;
  orders: number;
  totalSpend: number;
  lastLogin: string;
  status: "Active" | "Inactive";
};

const initialCustomers: Customer[] = [
  { id: "CUS-101", name: "Ayesha Khan", email: "ayesha@email.com", phone: "0300-1112233", orders: 12, totalSpend: 420500, lastLogin: "Today", status: "Active" },
  { id: "CUS-102", name: "Usman Tariq", email: "usman@email.com", phone: "0321-4455667", orders: 8, totalSpend: 298000, lastLogin: "Yesterday", status: "Active" },
  { id: "CUS-103", name: "Fatima Noor", email: "fatima@email.com", phone: "0333-7788990", orders: 5, totalSpend: 156200, lastLogin: "2 days ago", status: "Active" },
  { id: "CUS-104", name: "Ali Raza", email: "ali@email.com", phone: "0345-1122334", orders: 3, totalSpend: 78400, lastLogin: "1 week ago", status: "Inactive" },
  { id: "CUS-105", name: "Hira Aslam", email: "hira@email.com", phone: "0312-5566778", orders: 9, totalSpend: 265900, lastLogin: "Today", status: "Active" },
  { id: "CUS-106", name: "Bilal Ahmed", email: "bilal@email.com", phone: "0308-9988776", orders: 2, totalSpend: 41900, lastLogin: "3 days ago", status: "Active" },
  { id: "CUS-107", name: "Sana Javed", email: "sana@email.com", phone: "0331-2233445", orders: 6, totalSpend: 188750, lastLogin: "Yesterday", status: "Active" },
  { id: "CUS-108", name: "Omar Sheikh", email: "omar@email.com", phone: "0340-6677889", orders: 1, totalSpend: 28900, lastLogin: "2 weeks ago", status: "Inactive" },
];

export default function AdminCustomersPage() {
  const [customers, setCustomers] = useState(initialCustomers);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [message, setMessage] = useState("");
  const [selected, setSelected] = useState<Customer | null>(null);

  const filtered = useMemo(() => {
    return customers.filter((c) => {
      const q = search.toLowerCase();
      const matchesSearch =
        !q ||
        c.name.toLowerCase().includes(q) ||
        c.email.toLowerCase().includes(q) ||
        c.phone.includes(q);
      const matchesStatus = statusFilter === "all" || c.status === statusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [customers, search, statusFilter]);

  const stats = useMemo(() => {
    return {
      total: customers.length,
      active: customers.filter((c) => c.status === "Active").length,
      spend: customers.reduce((s, c) => s + c.totalSpend, 0),
      orders: customers.reduce((s, c) => s + c.orders, 0),
    };
  }, [customers]);

  const flash = (text: string) => {
    setMessage(text);
    window.setTimeout(() => setMessage(""), 2500);
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Customers"
        description="View customer profiles, order history, addresses, and loyalty data."
      />

      {message ? (
        <div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm text-emerald-800">
          {message}
        </div>
      ) : null}

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <StatCard label="Total Customers" value={stats.total} />
        <StatCard label="Active" value={stats.active} tone="success" />
        <StatCard label="Total Orders" value={stats.orders} tone="info" />
        <StatCard label="Lifetime Spend" value={formatCurrency(stats.spend)} />
      </div>

      <Panel title="Customer List">
        <FilterBar>
          <SearchInput value={search} onChange={setSearch} placeholder="Search name, email, phone…" />
          <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 customers found" description="Try another search or status filter." />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full min-w-[980px] 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">Name</th>
                  <th className="pb-2 font-semibold">Email</th>
                  <th className="pb-2 font-semibold">Phone</th>
                  <th className="pb-2 font-semibold">Orders</th>
                  <th className="pb-2 font-semibold">Total Spend</th>
                  <th className="pb-2 font-semibold">Last Login</th>
                  <th className="pb-2 font-semibold">Status</th>
                  <th className="pb-2 font-semibold">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((customer) => (
                  <tr key={customer.id} className="border-b border-border/60 align-top">
                    <td className="py-3 font-semibold">{customer.name}</td>
                    <td className="py-3 text-muted-foreground">{customer.email}</td>
                    <td className="py-3">{customer.phone}</td>
                    <td className="py-3">{customer.orders}</td>
                    <td className="py-3 font-semibold">{formatCurrency(customer.totalSpend)}</td>
                    <td className="py-3 text-muted-foreground">{customer.lastLogin}</td>
                    <td className="py-3">
                      <StatusBadge status={customer.status} />
                    </td>
                    <td className="py-3">
                      <div className="flex flex-wrap gap-1.5">
                        <AdminButton variant="secondary" onClick={() => setSelected(customer)}>View</AdminButton>
                        <AdminButton variant="ghost" onClick={() => flash(`Order history for ${customer.name}`)}>Order History</AdminButton>
                        <AdminButton variant="ghost" onClick={() => flash(`Addresses for ${customer.name}`)}>Addresses</AdminButton>
                        <AdminButton variant="ghost" onClick={() => flash(`Wishlist for ${customer.name}`)}>Wishlist</AdminButton>
                        <AdminButton variant="ghost" onClick={() => flash(`Reward points for ${customer.name}`)}>Reward Points</AdminButton>
                        <AdminButton variant="ghost" onClick={() => flash(`Coupons used by ${customer.name}`)}>Coupons Used</AdminButton>
                        <AdminButton
                          variant="secondary"
                          onClick={() => {
                            setCustomers((prev) =>
                              prev.map((c) =>
                                c.id === customer.id
                                  ? { ...c, status: c.status === "Active" ? "Inactive" : "Active" }
                                  : c,
                              ),
                            );
                            flash(`${customer.name} ${customer.status === "Active" ? "deactivated" : "activated"}`);
                          }}
                        >
                          {customer.status === "Active" ? "Deactivate" : "Activate"}
                        </AdminButton>
                        <AdminButton
                          variant="danger"
                          onClick={() => {
                            setCustomers((prev) => prev.filter((c) => c.id !== customer.id));
                            if (selected?.id === customer.id) setSelected(null);
                            flash(`${customer.name} deleted`);
                          }}
                        >
                          Delete
                        </AdminButton>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Panel>

      {selected ? (
        <Panel title={`Customer Detail — ${selected.name}`} actions={<AdminButton variant="ghost" onClick={() => setSelected(null)}>Close</AdminButton>}>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 text-sm">
            <div><p className="text-xs text-muted-foreground">Email</p><p className="font-medium">{selected.email}</p></div>
            <div><p className="text-xs text-muted-foreground">Phone</p><p className="font-medium">{selected.phone}</p></div>
            <div><p className="text-xs text-muted-foreground">Orders</p><p className="font-medium">{selected.orders}</p></div>
            <div><p className="text-xs text-muted-foreground">Total Spend</p><p className="font-medium">{formatCurrency(selected.totalSpend)}</p></div>
            <div><p className="text-xs text-muted-foreground">Last Login</p><p className="font-medium">{selected.lastLogin}</p></div>
            <div><p className="text-xs text-muted-foreground">Status</p><StatusBadge status={selected.status} /></div>
          </div>
        </Panel>
      ) : null}
    </div>
  );
}
