"use client";

import React, { useMemo, useState } from "react";
import { MagnifyingGlassIcon, ChevronDownIcon } from "@heroicons/react/24/outline";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { LoadingTable } from "@/components/atoms/loading-skeleton";
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 "@/lib/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, error } = invoicesQuery as {
    data?: { invoices: Invoice[]; pagination?: { totalItems: number; totalPages: number } };
    isLoading: 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,
      })),
    ],
    []
  );

  if (isLoading || error) {
    return (
      <SubCard>
        <AsyncBlock isLoading={false} error={error}>
          <LoadingTable rows={6} columns={5} />
        </AsyncBlock>
      </SubCard>
    );
  }

  return (
    <div className={cn("space-y-4", className)}>
      {/* Clean Header */}
      {showFilters && (
        <div className="bg-white/80 backdrop-blur-sm rounded-xl border border-gray-200/60 px-5 py-4 shadow-sm">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            {/* Title Section */}
            <div className="flex items-center gap-3">
              <h2 className="text-lg font-semibold text-gray-900">Invoices</h2>
              {pagination?.totalItems && (
                <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                  {pagination.totalItems} total
                </span>
              )}
            </div>

            {/* Controls */}
            <div className="flex items-center gap-3">
              {/* Search Input */}
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <MagnifyingGlassIcon className="h-4 w-4 text-gray-400" />
                </div>
                <input
                  type="text"
                  className="block w-64 pl-9 pr-4 py-2.5 text-sm border border-gray-200 rounded-lg bg-white/50 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 transition-all duration-200"
                  placeholder="Search invoices..."
                  value={searchTerm}
                  onChange={e => setSearchTerm(e.target.value)}
                />
              </div>

              {/* 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-36 pl-3 pr-8 py-2.5 text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-400 rounded-lg appearance-none bg-white/50 cursor-pointer transition-all duration-200"
                  >
                    {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-3 pointer-events-none">
                    <ChevronDownIcon className="h-4 w-4 text-gray-400" />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Invoice Table */}
      <div className="bg-white rounded-xl border border-gray-200/60 shadow-sm overflow-hidden">
        <InvoiceTable
          invoices={filtered}
          loading={isLoading}
          compact={compact}
          className="border-0 rounded-none shadow-none"
        />
        {pagination && filtered.length > 0 && (
          <div className="border-t border-gray-100 bg-gray-50/30 px-6 py-4">
            <PaginationBar
              currentPage={currentPage}
              pageSize={pageSize}
              totalItems={pagination?.totalItems || 0}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>
    </div>
  );
}

export type { InvoicesListProps };
