"use client";

import { useEffect, useMemo, useState } from "react";
import { AlertCircle, Search, Mail, Phone, CalendarClock, ShieldBan, ShieldCheck } from "lucide-react";
import { PageHeader } from "@/components/ui/PageHeader";
import { Avatar } from "@/components/ui/Avatar";
import { StatusBadge } from "@/components/ui/StatusBadge";
import { Drawer } from "@/components/ui/Drawer";
import { Button } from "@/components/ui/Button";
import { Pagination } from "@/components/ui/Pagination";
import { EmptyState } from "@/components/ui/EmptyState";
import { Skeleton } from "@/components/ui/Skeleton";
import { NetworkBadge } from "@/components/NetworkBadge";
import { formatCurrency, formatDate } from "@/lib/mock-data";
import { AdminCustomer, fetchCustomers, setCustomerStatus } from "@/lib/data/customers";
import { useAdminOrders } from "@/lib/data/admin-orders-provider";
import { UserStatus } from "@/lib/types";
import { NetworkId } from "@/lib/types";
import { cn } from "@/lib/cn";

const PAGE_SIZE = 8;
const TABS: { id: UserStatus | "all"; label: string }[] = [
  { id: "all", label: "All" },
  { id: "active", label: "Active" },
  { id: "blocked", label: "Blocked" },
];

export default function UsersPage() {
  const { orders } = useAdminOrders();
  const [customers, setCustomers] = useState<AdminCustomer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [tab, setTab] = useState<UserStatus | "all">("all");
  const [query, setQuery] = useState("");
  const [page, setPage] = useState(1);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [updatingStatus, setUpdatingStatus] = useState(false);

  async function load() {
    try {
      const result = await fetchCustomers();
      setCustomers(result);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't load users.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    load();
  }, []);

  const rows = useMemo(() => {
    return customers
      .filter((c) => tab === "all" || c.status === tab)
      .filter((c) => {
        if (!query.trim()) return true;
        const q = query.toLowerCase();
        return c.name.toLowerCase().includes(q) || c.phone.toLowerCase().includes(q);
      });
  }, [customers, tab, query]);

  const totalPages = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
  const pageRows = rows.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const selected = customers.find((c) => c.id === selectedId) ?? null;
  // Reused from the same context Orders/Dashboard/Payments already share —
  // filtered client-side by customerId rather than a second query.
  const selectedOrders = selected ? orders.filter((o) => o.customerId === selected.id) : [];

  async function toggleStatus(customer: AdminCustomer) {
    const next: UserStatus = customer.status === "active" ? "blocked" : "active";
    setUpdatingStatus(true);
    try {
      await setCustomerStatus(customer.id, next);
      setCustomers((prev) => prev.map((c) => (c.id === customer.id ? { ...c, status: next } : c)));
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't update that user.");
    } finally {
      setUpdatingStatus(false);
    }
  }

  return (
    <div>
      <PageHeader title="Users" subtitle="Everyone who's ever signed up" />

      {error && (
        <div className="mb-4 flex items-center gap-2 rounded-xl bg-danger/10 px-4 py-3 text-sm text-danger">
          <AlertCircle size={16} /> {error}
        </div>
      )}

      <div className="panel">
        <div className="flex flex-col gap-3 border-b border-black/[0.06] p-4 dark:border-white/[0.06] sm:flex-row sm:items-center sm:justify-between">
          <div className="flex gap-1.5">
            {TABS.map((t) => {
              const count = t.id === "all" ? customers.length : customers.filter((c) => c.status === t.id).length;
              return (
                <button
                  key={t.id}
                  onClick={() => {
                    setTab(t.id);
                    setPage(1);
                  }}
                  className={cn(
                    "rounded-xl px-3.5 py-2 text-sm font-medium transition-colors",
                    tab === t.id
                      ? "bg-gold text-ink font-semibold"
                      : "text-muted hover:bg-black/[0.03] dark:hover:bg-white/[0.04]"
                  )}
                >
                  {t.label} <span className="tnum opacity-70">({count})</span>
                </button>
              );
            })}
          </div>
          <div className="flex items-center gap-2 rounded-xl border border-black/[0.08] px-3 py-2 dark:border-white/[0.08] sm:w-64">
            <Search size={15} className="text-muted" />
            <input
              value={query}
              onChange={(e) => {
                setQuery(e.target.value);
                setPage(1);
              }}
              placeholder="Search users…"
              className="w-full bg-transparent text-sm outline-none placeholder:text-muted"
            />
          </div>
        </div>

        {loading ? (
          <div className="flex flex-col gap-2 p-4">
            {Array.from({ length: 5 }).map((_, i) => (
              <Skeleton key={i} className="h-14 w-full" />
            ))}
          </div>
        ) : pageRows.length === 0 ? (
          <EmptyState icon={Search} title="No users found" description="Try a different filter or search term." />
        ) : (
          <div className="thin-scrollbar overflow-x-auto">
            <table className="w-full min-w-[720px] text-left text-sm">
              <thead>
                <tr className="border-b border-black/[0.06] text-[11px] uppercase tracking-wide text-muted dark:border-white/[0.06]">
                  <th className="px-5 py-3 font-medium">Customer</th>
                  <th className="px-5 py-3 font-medium">Joined</th>
                  <th className="px-5 py-3 font-medium">Orders</th>
                  <th className="px-5 py-3 font-medium">Total Spent</th>
                  <th className="px-5 py-3 font-medium">Status</th>
                </tr>
              </thead>
              <tbody>
                {pageRows.map((c) => (
                  <tr
                    key={c.id}
                    onClick={() => setSelectedId(c.id)}
                    className="cursor-pointer border-b border-black/[0.04] transition-colors last:border-0 hover:bg-black/[0.015] dark:border-white/[0.04] dark:hover:bg-white/[0.02]"
                  >
                    <td className="px-5 py-3.5">
                      <div className="flex items-center gap-2.5">
                        <Avatar name={c.name} size="sm" />
                        <div className="min-w-0">
                          <p className="truncate text-[13px] font-medium">{c.name}</p>
                          <p className="truncate text-[11px] text-muted">{c.phone}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-5 py-3.5 text-[13px] text-muted">{formatDate(c.joinedAt)}</td>
                    <td className="px-5 py-3.5 tnum text-[13px] font-medium">{c.totalOrders}</td>
                    <td className="px-5 py-3.5 tnum text-[13px] font-semibold">
                      {formatCurrency(c.totalSpent)}
                    </td>
                    <td className="px-5 py-3.5">
                      <span
                        className={cn(
                          "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-semibold",
                          c.status === "active" ? "bg-success/12 text-success" : "bg-danger/12 text-danger"
                        )}
                      >
                        {c.status === "active" ? "Active" : "Blocked"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        <Pagination page={page} totalPages={totalPages} onChange={setPage} totalItems={rows.length} pageSize={PAGE_SIZE} />
      </div>

      <Drawer
        open={!!selected}
        onClose={() => setSelectedId(null)}
        title={selected?.name ?? ""}
        subtitle={selected?.id}
        footer={
          selected && (
            <Button
              fullWidth
              variant={selected.status === "active" ? "danger" : "primary"}
              disabled={updatingStatus}
              onClick={() => toggleStatus(selected)}
            >
              {selected.status === "active" ? (
                <>
                  <ShieldBan size={15} /> Block User
                </>
              ) : (
                <>
                  <ShieldCheck size={15} /> Unblock User
                </>
              )}
            </Button>
          )
        }
      >
        {selected && (
          <div className="flex flex-col gap-5">
            <div className="flex items-center gap-3">
              <Avatar name={selected.name} size="lg" />
              <div>
                <p className="font-display text-base font-semibold">{selected.name}</p>
                <span
                  className={cn(
                    "mt-1 inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold",
                    selected.status === "active" ? "bg-success/12 text-success" : "bg-danger/12 text-danger"
                  )}
                >
                  {selected.status === "active" ? "Active" : "Blocked"}
                </span>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div className="panel !shadow-none p-3.5 text-center">
                <p className="tnum font-display text-lg font-bold">{selected.totalOrders}</p>
                <p className="text-[11px] text-muted">Total Orders</p>
              </div>
              <div className="panel !shadow-none p-3.5 text-center">
                <p className="tnum font-display text-lg font-bold">{formatCurrency(selected.totalSpent)}</p>
                <p className="text-[11px] text-muted">Total Spent</p>
              </div>
            </div>

            <div className="flex flex-col gap-3 rounded-2xl border border-black/[0.06] p-4 dark:border-white/[0.06]">
              <div className="flex items-center gap-2 text-sm">
                <Phone size={14} className="text-muted" /> {selected.phone}
              </div>
              {selected.email && (
                <div className="flex items-center gap-2 text-sm">
                  <Mail size={14} className="text-muted" /> {selected.email}
                </div>
              )}
              <div className="flex items-center gap-2 text-sm">
                <CalendarClock size={14} className="text-muted" /> Joined {formatDate(selected.joinedAt)}
              </div>
            </div>

            <div>
              <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted">
                Order History ({selectedOrders.length})
              </p>
              <div className="flex flex-col gap-2">
                {selectedOrders.length === 0 && (
                  <p className="py-6 text-center text-xs text-muted">No orders yet.</p>
                )}
                {selectedOrders.map((o) => (
                  <div
                    key={o.dbId}
                    className="flex items-center gap-3 rounded-2xl border border-black/[0.06] p-3 dark:border-white/[0.06]"
                  >
                    <NetworkBadge network={o.network as NetworkId} size="sm" />
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-[13px] font-medium">{o.packageName}</p>
                      <p className="text-[11px] text-muted">{formatDate(o.createdAt)}</p>
                    </div>
                    <StatusBadge status={o.status} compact />
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}
