"use client";

import { useMemo, useState, useTransition } from "react";
import { CreditCard, ExternalLink, Filter, Loader2, ReceiptText, Search, Trash2, TrendingUp, Users, X } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Container } from "@/components/container";
import { useLanguage } from "@/lib/i18n/context";
import { PLANS } from "@/config/plans";
import {
  deleteCustomerAccountAction,
  listAdminInvoicesAction,
  type AdminInvoice,
} from "@/actions/admin-users-actions";
import type { AdminCustomerRow, AdminCustomerSummary } from "@/database/admin-users";

function formatMoney(value: number, locale: "en" | "es"): string {
  return new Intl.NumberFormat(locale === "es" ? "es-US" : "en-US", {
    style: "currency",
    currency: "USD",
    maximumFractionDigits: 2,
  }).format(value);
}

function formatDate(value: Date | number | null, locale: "en" | "es"): string {
  if (!value) return "—";
  const date = typeof value === "number" ? new Date(value * 1000) : new Date(value);
  return new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", {
    dateStyle: "medium",
  }).format(date);
}

function invoiceStatusClass(status: string | null): string {
  if (status === "paid") return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700";
  if (status === "open" || status === "draft") return "border-amber-500/30 bg-amber-500/10 text-amber-700";
  return "border-border bg-muted/50 text-muted-foreground";
}

function accountStatusClass(status: AdminCustomerRow["status"]): string {
  if (status === "ACTIVE") return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700";
  if (status === "SUSPENDED") return "border-amber-500/30 bg-amber-500/10 text-amber-700";
  return "border-slate-500/30 bg-slate-500/10 text-slate-600";
}

function subscriptionStatusClass(status: AdminCustomerRow["subscriptionStatus"]): string {
  if (status === "ACTIVE" || status === "TRIALING") return "border-emerald-500/30 bg-emerald-500/10 text-emerald-700";
  if (status === "PAST_DUE" || status === "UNPAID" || status === "INCOMPLETE") return "border-amber-500/30 bg-amber-500/10 text-amber-700";
  if (status === "CANCELED" || status === "INCOMPLETE_EXPIRED") return "border-slate-500/30 bg-slate-500/10 text-slate-600";
  return "border-border bg-muted/50 text-muted-foreground";
}

function SummaryCard({ icon: Icon, label, value, accent }: { icon: typeof Users; label: string; value: string; accent: string }) {
  return (
    <Card className="admin-surface admin-stat-card overflow-hidden rounded-2xl border-border/70 shadow-sm">
      <CardContent className="flex items-center gap-3 p-5">
        <span className={`flex size-10 items-center justify-center rounded-xl ${accent}`}>
          <Icon className="size-5" />
        </span>
        <div>
          <p className="text-xs font-medium text-muted-foreground">{label}</p>
          <p className="mt-1 text-2xl font-semibold tracking-tight text-foreground">{value}</p>
        </div>
      </CardContent>
    </Card>
  );
}

function InvoicePanel({
  customer,
  invoices,
  loading,
  onClose,
}: {
  customer: AdminCustomerRow;
  invoices: AdminInvoice[];
  loading: boolean;
  onClose: () => void;
}) {
  const { t, locale } = useLanguage();
  const u = t.admin.users;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/30 p-4 backdrop-blur-sm" role="dialog" aria-modal="true">
      <div className="max-h-[85vh] w-full max-w-3xl overflow-hidden rounded-2xl border border-border bg-background shadow-2xl">
        <div className="flex items-start justify-between gap-4 border-b border-border px-6 py-5">
          <div>
            <p className="text-xs font-semibold tracking-[0.18em] text-primary uppercase">{u.invoiceTitle}</p>
            <h2 className="mt-1 text-lg font-semibold text-foreground">{customer.name || `${customer.firstName} ${customer.lastName}`}</h2>
            <p className="text-sm text-muted-foreground">{customer.email}</p>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose} aria-label={u.close}>
            <X className="size-4" />
          </Button>
        </div>

        <div className="max-h-[65vh] overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground">
              <Loader2 className="size-4 animate-spin" /> {u.loading}
            </div>
          ) : invoices.length === 0 ? (
            <p className="py-12 text-center text-sm text-muted-foreground">{u.noInvoices}</p>
          ) : (
            <div className="overflow-x-auto rounded-xl border border-border/70">
              <table className="admin-invoice-table w-full min-w-[720px] table-fixed text-left text-sm">
                <colgroup>
                  <col style={{ width: "17%" }} />
                  <col style={{ width: "15%" }} />
                  <col style={{ width: "28%" }} />
                  <col style={{ width: "14%" }} />
                  <col style={{ width: "13%" }} />
                  <col style={{ width: "13%" }} />
                </colgroup>
                <thead className="bg-muted/40 text-xs text-muted-foreground">
                  <tr>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.invoiceNumber}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.invoiceDate}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.invoicePeriod}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.invoiceStatus}</th>
                    <th className="whitespace-nowrap px-4 py-3 text-right font-medium">{u.invoiceAmount}</th>
                    <th className="px-4 py-3" />
                  </tr>
                </thead>
                <tbody>
                  {invoices.map((invoice) => (
                    <tr key={invoice.id} className="border-t border-border/60">
                      <td className="truncate px-4 py-3 font-medium text-foreground">{invoice.number ?? invoice.id}</td>
                      <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">{formatDate(invoice.createdAt, locale)}</td>
                      <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">
                        {invoice.periodStart && invoice.periodEnd
                          ? `${formatDate(invoice.periodStart, locale)} – ${formatDate(invoice.periodEnd, locale)}`
                          : "—"}
                      </td>
                      <td className="px-4 py-3">
                        <Badge variant="outline" className={invoiceStatusClass(invoice.status)}>{invoice.status ?? "—"}</Badge>
                      </td>
                      <td className="whitespace-nowrap px-4 py-3 text-right font-medium tabular-nums text-foreground">
                        {formatMoney((invoice.amountPaid || invoice.total || invoice.amountDue) / 100, locale)}
                      </td>
                      <td className="px-4 py-3 text-right">
                        {(invoice.hostedInvoiceUrl || invoice.invoicePdf) && (
                          <Button asChild variant="ghost" size="sm">
                            <a href={invoice.hostedInvoiceUrl ?? invoice.invoicePdf ?? "#"} target="_blank" rel="noreferrer">
                              <ExternalLink className="size-3.5" /> {u.openInvoice}
                            </a>
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export function AdminUsersContent({ customers, summary }: { customers: AdminCustomerRow[]; summary: AdminCustomerSummary }) {
  const { t, locale } = useLanguage();
  const u = t.admin.users;
  const [isPending, startTransition] = useTransition();
  const [selectedCustomer, setSelectedCustomer] = useState<AdminCustomerRow | null>(null);
  const [invoices, setInvoices] = useState<AdminInvoice[]>([]);
  const [invoiceLoading, setInvoiceLoading] = useState(false);
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<"ALL" | AdminCustomerRow["status"]>("ALL");
  const [planFilter, setPlanFilter] = useState<"ALL" | AdminCustomerRow["plan"]>("ALL");

  function planName(plan: AdminCustomerRow["plan"]): string {
    return t.plans[PLANS[plan].translationKey].name;
  }

  function accountStatusLabel(status: AdminCustomerRow["status"]): string {
    if (status === "DELETED") return u.deleted;
    if (status === "SUSPENDED") return u.suspended;
    return u.active;
  }

  function subscriptionLabel(customer: AdminCustomerRow): string {
    if (!customer.subscriptionStatus || customer.subscriptionStatus === "FREE") return u.noPlan;
    const labels: Record<string, string> = {
      ACTIVE: u.active,
      TRIALING: u.trialing,
      PAST_DUE: u.pastDue,
      UNPAID: u.unpaid,
      INCOMPLETE: u.incomplete,
      CANCELED: u.canceled,
    };
    return labels[customer.subscriptionStatus] ?? customer.subscriptionStatus;
  }

  const filteredCustomers = useMemo(() => {
    const normalizedQuery = query.trim().toLowerCase();
    return customers.filter((customer) => {
      const matchesQuery = !normalizedQuery || [customer.name, customer.email, customer.firstName, customer.lastName]
        .filter(Boolean)
        .some((value) => value!.toLowerCase().includes(normalizedQuery));
      const matchesStatus = statusFilter === "ALL" || customer.status === statusFilter;
      const matchesPlan = planFilter === "ALL" || customer.plan === planFilter;
      return matchesQuery && matchesStatus && matchesPlan;
    });
  }, [customers, planFilter, query, statusFilter]);

  const filtersActive = query.trim().length > 0 || statusFilter !== "ALL" || planFilter !== "ALL";

  function openInvoices(customer: AdminCustomerRow) {
    setSelectedCustomer(customer);
    setInvoices([]);
    setInvoiceLoading(true);
    startTransition(async () => {
      const result = await listAdminInvoicesAction(customer.id, locale);
      setInvoiceLoading(false);
      if (result.success) setInvoices(result.invoices);
      else toast.error(result.error);
    });
  }

  function deleteCustomer(customer: AdminCustomerRow) {
    if (customer.role === "ADMIN" || !window.confirm(u.confirmDelete)) return;
    startTransition(async () => {
      const result = await deleteCustomerAccountAction(customer.id, locale);
      if (result.success) {
        toast.success(result.message ?? u.deleteSuccess);
        window.location.reload();
      } else {
        toast.error(result.error);
      }
    });
  }

  const dateFormatter = new Intl.DateTimeFormat(locale === "es" ? "es-US" : "en-US", { dateStyle: "medium" });

  return (
    <div className="admin-page py-8">
      <Container className="flex flex-col gap-6">
        <div className="admin-page-intro">
          <h2>{u.title}</h2>
          <p className="mt-1 max-w-3xl text-sm text-muted-foreground">{u.description}</p>
        </div>

        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          <SummaryCard icon={Users} label={u.totalUsers} value={String(summary.totalUsers)} accent="bg-primary/10 text-primary" />
          <SummaryCard icon={TrendingUp} label={u.activeUsers} value={String(summary.activeUsers)} accent="bg-emerald-500/10 text-emerald-600" />
          <SummaryCard icon={CreditCard} label={u.paidPlans} value={String(summary.paidPlans)} accent="bg-violet-500/10 text-violet-600" />
          <SummaryCard icon={ReceiptText} label={u.projectedMrr} value={formatMoney(summary.projectedMrr, locale)} accent="bg-amber-500/10 text-amber-600" />
        </div>

        <Card className="admin-surface overflow-hidden rounded-2xl border-border/70 shadow-sm">
          <CardHeader className="border-b border-border/70 bg-muted/10 px-6 py-5">
            <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
              <div>
                <CardTitle className="text-base">{u.customerDirectory}</CardTitle>
                <p className="mt-1 text-xs text-muted-foreground">{filteredCustomers.length} / {customers.length}</p>
              </div>
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                <label className="relative min-w-64">
                  <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                  <span className="sr-only">{u.search}</span>
                  <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder={u.search} className="h-10 w-full rounded-lg border border-border bg-background pr-3 pl-9 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15" />
                </label>
                <label className="relative">
                  <Filter className="pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted-foreground" />
                  <span className="sr-only">{u.accountStatus}</span>
                  <select value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as typeof statusFilter)} className="h-10 appearance-none rounded-lg border border-border bg-background pr-8 pl-9 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/15">
                    <option value="ALL">{u.allStatuses}</option>
                    <option value="ACTIVE">{u.active}</option>
                    <option value="SUSPENDED">{u.suspended}</option>
                    <option value="DELETED">{u.deleted}</option>
                  </select>
                </label>
                <label>
                  <span className="sr-only">{u.plan}</span>
                  <select value={planFilter} onChange={(event) => setPlanFilter(event.target.value as typeof planFilter)} className="h-10 rounded-lg border border-border bg-background px-3 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/15">
                    <option value="ALL">{u.allPlans}</option>
                    <option value="FREE">{planName("FREE")}</option>
                    <option value="PRO">{planName("PRO")}</option>
                    <option value="AGENCY">{planName("AGENCY")}</option>
                  </select>
                </label>
                {filtersActive && <Button variant="ghost" size="sm" onClick={() => { setQuery(""); setStatusFilter("ALL"); setPlanFilter("ALL"); }}>{u.clearFilters}</Button>}
              </div>
            </div>
          </CardHeader>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <table className="admin-customer-table w-full min-w-[1355px] table-fixed text-left text-sm">
                <colgroup>
                  <col style={{ width: 270 }} />
                  <col style={{ width: 120 }} />
                  <col style={{ width: 225 }} />
                  <col style={{ width: 105 }} />
                  <col style={{ width: 145 }} />
                  <col style={{ width: 150 }} />
                  <col style={{ width: 150 }} />
                  <col style={{ width: 190 }} />
                </colgroup>
                <thead className="bg-muted/35 text-xs text-muted-foreground">
                  <tr>
                    <th className="whitespace-nowrap px-6 py-3 font-medium">{u.user}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.accountStatus}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.plan}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.interval}</th>
                    <th className="whitespace-nowrap px-4 py-3 text-right font-medium">{u.projectedMonthly}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.renewal}</th>
                    <th className="whitespace-nowrap px-4 py-3 font-medium">{u.lastActive}</th>
                    <th className="whitespace-nowrap px-6 py-3 text-right font-medium">{u.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredCustomers.length === 0 ? (
                    <tr><td colSpan={8} className="px-6 py-14 text-center text-sm text-muted-foreground">{customers.length === 0 ? u.noUsers : u.noMatches}</td></tr>
                  ) : filteredCustomers.map((customer) => (
                    <tr key={customer.id} className="h-[104px] border-t border-border/60 align-middle">
                      <td className="px-6 py-3">
                        <p className="truncate font-medium text-foreground">{customer.name || `${customer.firstName} ${customer.lastName}`}</p>
                        <p className="mt-0.5 max-w-[235px] truncate text-xs text-muted-foreground">{customer.email}</p>
                        <p className="mt-1 whitespace-nowrap text-[11px] text-muted-foreground">{u.memberSince} {dateFormatter.format(new Date(customer.createdAt))}</p>
                      </td>
                      <td className="whitespace-nowrap px-4 py-3"><Badge variant="outline" className={accountStatusClass(customer.status)}>{accountStatusLabel(customer.status)}</Badge></td>
                      <td className="px-4 py-3">
                        <p className="whitespace-nowrap font-medium text-foreground">{planName(customer.plan)}</p>
                        <p className="mt-1 flex items-center gap-1 whitespace-nowrap text-[11px] text-muted-foreground">
                          <span className={`size-1.5 rounded-full ${customer.stripeCustomerLinked ? "bg-emerald-500" : "bg-slate-300"}`} />
                          {customer.stripeCustomerLinked ? u.linked : u.notLinked}
                        </p>
                        <Badge variant="outline" className={`mt-2 whitespace-nowrap ${subscriptionStatusClass(customer.subscriptionStatus)}`}>{subscriptionLabel(customer)}</Badge>
                      </td>
                      <td className="px-4 py-4 text-muted-foreground">{customer.billingInterval === "ANNUAL" ? u.annual : customer.billingInterval === "MONTHLY" ? u.monthly : "—"}</td>
                      <td className="whitespace-nowrap px-4 py-3 text-right font-medium tabular-nums text-foreground">
                        {customer.projectedMonthly > 0 ? formatMoney(customer.projectedMonthly, locale) : "—"}
                      </td>
                      <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">{formatDate(customer.currentPeriodEnd, locale)}</td>
                      <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">{formatDate(customer.lastLoginAt, locale)}</td>
                      <td className="px-6 py-3">
                        <div className="flex flex-nowrap justify-end gap-2">
                          <Button variant="outline" size="sm" className="whitespace-nowrap" onClick={() => openInvoices(customer)} disabled={isPending}>
                            <ReceiptText className="size-3.5" /> {u.invoices}
                          </Button>
                          {customer.role !== "ADMIN" && customer.status !== "DELETED" && (
                            <Button variant="ghost" size="icon" className="text-destructive hover:bg-destructive/10 hover:text-destructive" onClick={() => deleteCustomer(customer)} disabled={isPending} aria-label={u.deleteAccount}>
                              <Trash2 className="size-4" />
                            </Button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </CardContent>
        </Card>
      </Container>
      {selectedCustomer && (
        <InvoicePanel customer={selectedCustomer} invoices={invoices} loading={invoiceLoading} onClose={() => setSelectedCustomer(null)} />
      )}
    </div>
  );
}
