"use client";

import React, { useMemo, useState } from "react";
import { MagnifyingGlassIcon, ChevronDownIcon } from "@heroicons/react/24/outline";
import { Spinner } from "@/components/atoms";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { PaginationBar } from "@/components/molecules/PaginationBar/PaginationBar";
import { InvoiceTable } from "@/features/billing/components/InvoiceTable/InvoiceTable";
import { useInvoices } from "@/features/billing/hooks/useBilling";
import { useSubscriptionInvoices } from "@/features/subscriptions/hooks/useSubscriptions";
import { INVOICE_STATUS, type Invoice, type InvoiceStatus } from "@customer-portal/domain/billing";
import { cn } from "@/shared/utils";

interface InvoicesListProps {
  subscriptionId?: number;
  pageSize?: number;
  showFilters?: boolean;
  compact?: boolean;
  className?: string;
}

const INVOICE_STATUS_OPTIONS = Object.values(INVOICE_STATUS) as InvoiceStatus[];

export function InvoicesList({
  subscriptionId,
  pageSize = 10,
  showFilters = true,
  compact = false,
  className,
}: InvoicesListProps) {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<InvoiceStatus | "all">("all");
  const [currentPage, setCurrentPage] = useState(1);

  const isSubscriptionMode = typeof subscriptionId === "number" && !Number.isNaN(subscriptionId);

  // Call hooks unconditionally to satisfy React Hooks rules; use enabled to control fetching
  const subscriptionInvoicesQuery = useSubscriptionInvoices(subscriptionId ?? 0, {
    page: currentPage,
    limit: pageSize,
  });
  const allInvoicesQuery = useInvoices(
    {
      page: currentPage,
      limit: pageSize,
      status: statusFilter === "all" ? undefined : (statusFilter as InvoiceStatus),
    },
    { enabled: !isSubscriptionMode }
  );

  const invoicesQuery = isSubscriptionMode ? subscriptionInvoicesQuery : allInvoicesQuery;

  const { data, isLoading, isPending, error } = invoicesQuery as {
    data?: { invoices: Invoice[]; pagination?: { totalItems: number; totalPages: number } };
    isLoading: boolean;
    isPending: boolean;
    error: unknown;
  };

  const rawInvoices = data?.invoices;
  const invoices = useMemo(() => rawInvoices ?? [], [rawInvoices]);
  const pagination = data?.pagination;

  const filtered = useMemo(() => {
    if (!searchTerm) return invoices;
    const term = searchTerm.toLowerCase();
    return invoices.filter(inv => {
      return (
        inv.number.toLowerCase().includes(term) ||
        (inv.description ? inv.description.toLowerCase().includes(term) : false)
      );
    });
  }, [invoices, searchTerm]);

  const statusFilterOptions = useMemo(
    () => [
      { value: "all" as const, label: "All Status" },
      ...INVOICE_STATUS_OPTIONS.map(status => ({
        value: status,
        label: status,
      })),
    ],
    []
  );

  // Loading state - show centered spinner
  if (isPending) {
    return (
      <div className="bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)] overflow-hidden">
        <div className="flex items-center justify-center py-16">
          <Spinner size="lg" className="text-primary" />
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)] overflow-hidden">
        <AsyncBlock isLoading={false} error={error}>
          <div />
        </AsyncBlock>
      </div>
    );
  }

  return (
    <div
      className={cn(
        "bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)] overflow-hidden",
        className
      )}
    >
      {/* Search/Filter Header */}
      {showFilters && (
        <div className="px-6 py-4 border-b border-border">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            {/* Search Input */}
            <div className="relative flex-1 max-w-sm">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <MagnifyingGlassIcon className="h-5 w-5 text-muted-foreground" />
              </div>
              <input
                type="text"
                className="block w-full pl-10 pr-3 py-2.5 text-sm border border-border rounded-lg bg-card shadow-sm placeholder-muted-foreground text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary transition-colors"
                placeholder="Search invoices..."
                value={searchTerm}
                onChange={e => setSearchTerm(e.target.value)}
              />
            </div>

            {/* Controls */}
            <div className="flex items-center gap-3">
              {/* Total Count */}
              {pagination?.totalItems && (
                <span className="text-sm text-muted-foreground">
                  {pagination.totalItems} invoice{pagination.totalItems === 1 ? "" : "s"}
                </span>
              )}

              {/* Filter Dropdown */}
              {!isSubscriptionMode && (
                <div className="relative">
                  <select
                    value={statusFilter}
                    onChange={e => {
                      const nextValue = e.target.value as InvoiceStatus | "all";
                      setStatusFilter(nextValue);
                      setCurrentPage(1);
                    }}
                    className="block w-40 pl-3 pr-8 py-2.5 text-sm border border-border focus:outline-none focus:ring-2 focus:ring-ring focus:border-primary rounded-lg appearance-none bg-card shadow-sm text-foreground cursor-pointer transition-colors"
                  >
                    {statusFilterOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <div className="absolute inset-y-0 right-0 flex items-center pr-2.5 pointer-events-none">
                    <ChevronDownIcon className="h-4 w-4 text-muted-foreground" />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Invoice Table */}
      <InvoiceTable
        invoices={filtered}
        loading={isLoading}
        compact={compact}
        className="border-0 rounded-none shadow-none"
      />

      {/* Pagination */}
      {pagination && filtered.length > 0 && (
        <div className="border-t border-border px-6 py-4">
          <PaginationBar
            currentPage={currentPage}
            pageSize={pageSize}
            totalItems={pagination?.totalItems || 0}
            onPageChange={setCurrentPage}
          />
        </div>
      )}
    </div>
  );
}

export type { InvoicesListProps };
