import { useMemo, useState } from "react";
import {
  AlertCircle,
  Clock,
  DollarSign,
  Download,
  Filter,
  MoreHorizontal,
  Pencil,
  Plus,
  Receipt,
  Search,
  Trash2,
} from "lucide-react";

import Breadcrumbs from "@/components/Breadcrumbs";
import NewInvoicePage from "./NewInvoicePage";
import DeleteInvoiceDialog from "./DeleteInvoiceDialog";
import { formatCurrency, invoices, type InvoiceStatus } from "./invoices.mock";
import {
  DataTable,
  DataTableFooter,
  type ColumnDef,
  usePagination,
  Button,
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
  Input,
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
} from "@edr/ui-common";

type FilterValue = "All" | InvoiceStatus;

const FILTERS: FilterValue[] = [
  "All",
  "Draft",
  "Sent",
  "Paid",
  "Overdue",
  "Cancelled",
];

export default function BillingPage() {
  const { pagination, setPagination } = usePagination({ pageSize: 10 });
  const [filter, setFilter] = useState<FilterValue>("All");
  const [query, setQuery] = useState("");

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return invoices.filter((inv) => {
      if (filter !== "All" && inv.status !== filter) return false;
      if (!q) return true;
      return (
        inv.number.toLowerCase().includes(q) ||
        inv.customer.toLowerCase().includes(q) ||
        inv.bookingReference.toLowerCase().includes(q)
      );
    });
  }, [filter, query]);

  const total = filtered.length;
  const pageCount = Math.ceil(total / pagination.pageSize);
  const start = pagination.pageIndex * pagination.pageSize;
  const end = Math.min(start + pagination.pageSize, total);

  const paginatedData = useMemo(
    () => filtered.slice(start, end),
    [start, end, filtered],
  );

  const totalRevenue = invoices
    .filter((inv) => inv.status === "Paid" && inv.currency === "USD")
    .reduce((sum, inv) => sum + inv.amount, 0);
  const outstanding = invoices
    .filter(
      (inv) =>
        (inv.status === "Sent" || inv.status === "Overdue") &&
        inv.currency === "USD",
    )
    .reduce((sum, inv) => sum + inv.amount, 0);
  const overdueCount = invoices.filter(
    (inv) => inv.status === "Overdue",
  ).length;

  const columns: ColumnDef<(typeof invoices)[number]>[] = [
    {
      id: "invoice",
      header: "Invoice",
      cell: ({ row }) => {
        const inv = row.original;
        return (
          <div className="flex items-center gap-3">
            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
              <Receipt />
            </div>
            <div>
              <p className="font-medium text-slate-900">{inv.number}</p>
              <p className="text-sm text-slate-500">Issued {inv.issueDate}</p>
            </div>
          </div>
        );
      },
    },
    {
      accessorKey: "customer",
      header: "Customer",
    },
    {
      accessorKey: "bookingReference",
      header: "Booking",
    },
    {
      id: "amount",
      header: "Amount",
      cell: ({ row }) => {
        const inv = row.original;
        return (
          <span className="text-sm font-medium text-slate-900">
            {formatCurrency(inv.amount, inv.currency)}
          </span>
        );
      },
    },
    {
      accessorKey: "dueDate",
      header: "Due Date",
    },
    {
      accessorKey: "status",
      header: "Status",
      cell: ({ row }) => <StatusBadge status={row.original.status} />,
    },
    {
      id: "actions",
      size: 40,
      cell: ({ row }) => {
        const invoice = row.original;
        return (
          <div
            className="flex justify-end"
            onClick={(e) => e.stopPropagation()}
          >
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="icon">
                  <MoreHorizontal />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem>
                  <Download />
                  Download
                </DropdownMenuItem>
                <NewInvoicePage
                  mode="edit"
                  invoice={{
                    number: invoice.number,
                    customerId: invoice.customerId,
                    bookingReference: invoice.bookingReference,
                    amount: invoice.amount,
                    currency: invoice.currency,
                    status: invoice.status,
                    issueDate: invoice.issueDate,
                    dueDate: invoice.dueDate,
                    notes: invoice.notes,
                  }}
                >
                  <DropdownMenuItem onSelect={(e: Event) => e.preventDefault()}>
                    <Pencil />
                    Edit
                  </DropdownMenuItem>
                </NewInvoicePage>
                <DropdownMenuSeparator />
                <DeleteInvoiceDialog invoiceNumber={invoice.number}>
                  <DropdownMenuItem
                    onSelect={(e: Event) => e.preventDefault()}
                    variant="destructive"
                  >
                    <Trash2 />
                    Void
                  </DropdownMenuItem>
                </DeleteInvoiceDialog>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        );
      },
    },
  ];

  return (
    <div className="min-h-screen p-6">
      <div className="space-y-6">
        <Breadcrumbs items={[{ label: "Billing" }]} />

        <Card className="p-6 flex-row justify-between">
          <div>
            <h1 className="text-3xl font-bold tracking-tight text-slate-900">
              Billing
            </h1>
            <p className="mt-1 text-sm text-secondary-foreground">
              Manage invoices, payments, and financial records.
            </p>
          </div>

          <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:items-center">
            <div className="relative w-full sm:w-80">
              <Search className="pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
              <Input
                type="search"
                value={query}
                onChange={(e) => {
                  setQuery(e.target.value);
                  setPagination({
                    pageIndex: 0,
                    pageSize: pagination.pageSize,
                  });
                }}
                placeholder="Search invoices..."
                className="pl-8!"
              />
            </div>

            <NewInvoicePage>
              <Button>
                <Plus />
                New Invoice
              </Button>
            </NewInvoicePage>
          </div>
        </Card>

        <div className="grid gap-4 md:grid-cols-3">
          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Total Revenue (USD)</p>
                <h3 className="mt-2 text-3xl font-bold text-slate-900">
                  {formatCurrency(totalRevenue, "USD")}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <DollarSign />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Outstanding (USD)</p>
                <h3 className="mt-2 text-3xl font-bold text-slate-900">
                  {formatCurrency(outstanding, "USD")}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                <Clock />
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="flex items-center justify-between">
              <div>
                <p className="text-sm text-slate-500">Overdue Invoices</p>
                <h3 className="mt-2 text-3xl font-bold text-slate-900">
                  {overdueCount}
                </h3>
              </div>
              <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-red-100 text-red-600">
                <AlertCircle />
              </div>
            </CardContent>
          </Card>
        </div>

        <Card className="p-2">
          <div className="flex flex-wrap gap-1">
            {FILTERS.map((f) => {
              const isActive = f === filter;
              const count =
                f === "All"
                  ? invoices.length
                  : invoices.filter((inv) => inv.status === f).length;
              return (
                <button
                  key={f}
                  type="button"
                  onClick={() => {
                    setFilter(f);
                    setPagination({
                      pageIndex: 0,
                      pageSize: pagination.pageSize,
                    });
                  }}
                  className={
                    isActive
                      ? "inline-flex items-center gap-2 rounded-2xl bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
                      : "inline-flex items-center gap-2 rounded-2xl px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-primary/10 hover:text-primary"
                  }
                >
                  {f}
                  <span
                    className={
                      isActive
                        ? "rounded-full bg-white/20 px-2 py-0.5 text-xs"
                        : "rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600"
                    }
                  >
                    {count}
                  </span>
                </button>
              );
            })}
          </div>
        </Card>

        <Card className="gap-0">
          <CardHeader className="flex flex-row items-center justify-between border-b">
            <div>
              <CardTitle>Invoices</CardTitle>
              <CardDescription>
                Issued invoices and their payment status.
              </CardDescription>
            </div>

            <Button variant="secondary" size="sm">
              <Filter />
              Filter
            </Button>
          </CardHeader>

          <CardContent className="px-0">
            <DataTable
              columns={columns}
              data={paginatedData}
              status="success"
              onRowClick={() => { }}
              pagination={{
                pageIndex: pagination.pageIndex,
                pageSize: pagination.pageSize,
                pageCount: pageCount,
                totalCount: total,
              }}
              tableOptions={{
                state: { pagination },
                onPaginationChange: setPagination,
              }}
              containerClassName="border-b shadow-none"
              footer={DataTableFooter}
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function StatusBadge({ status }: { status: InvoiceStatus }) {
  const styles: Record<InvoiceStatus, string> = {
    Draft: "bg-slate-100 text-slate-600",
    Sent: "bg-sky-100 text-sky-700",
    Paid: "bg-emerald-100 text-emerald-700",
    Overdue: "bg-red-100 text-red-700",
    Cancelled: "bg-amber-100 text-amber-700",
  };

  return (
    <span
      className={`inline-flex rounded-full px-3 py-1 text-xs font-medium ${styles[status]}`}
    >
      {status}
    </span>
  );
}
