"use client";

import React, { useMemo, useState } from "react";
import {
  DocumentTextIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";
import { Spinner } from "@/components/atoms";
import { SummaryStats, ClearFiltersButton } from "@/components/molecules";
import type { StatItem } from "@/components/molecules/SummaryStats";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { PaginationBar } from "@/components/molecules/PaginationBar/PaginationBar";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import { InvoiceTable } from "@/features/billing/components/InvoiceTable/InvoiceTable";
import { useInvoices } from "@/features/billing/hooks/useBilling";
import { useSubscriptionInvoices } from "@/features/subscriptions/hooks/useSubscriptions";
import {
  VALID_INVOICE_QUERY_STATUSES,
  type Invoice,
  type InvoiceQueryStatus,
} 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 = [
  { value: "all", label: "All Statuses" },
  ...VALID_INVOICE_QUERY_STATUSES.map(status => ({
    value: status,
    label: status,
  })),
];

export function InvoicesList({
  subscriptionId,
  pageSize = 10,
  showFilters = true,
  compact = false,
  className,
}: InvoicesListProps) {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<InvoiceQueryStatus | "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,
    },
    { 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;

  // Client-side search filtering on loaded invoices
  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]);

  // Compute stats from loaded invoices
  const stats = useMemo(() => {
    const result = { total: 0, paid: 0, unpaid: 0, overdue: 0 };
    if (!invoices || invoices.length === 0) return result;

    for (const invoice of invoices) {
      result.total++;
      if (invoice.status === "Paid") result.paid++;
      else if (invoice.status === "Unpaid") result.unpaid++;
      else if (invoice.status === "Overdue") result.overdue++;
    }
    return result;
  }, [invoices]);

  const summaryStatsItems = useMemo<StatItem[]>(
    () => [
      {
        icon: <DocumentTextIcon className="h-4 w-4" />,
        label: "Total",
        value: pagination?.totalItems ?? stats.total,
        tone: "muted",
      },
      {
        icon: <CheckCircleIcon className="h-4 w-4" />,
        label: "Paid",
        value: stats.paid,
        tone: "success",
      },
      {
        icon: <ClockIcon className="h-4 w-4" />,
        label: "Unpaid",
        value: stats.unpaid,
        tone: "warning",
        show: stats.unpaid > 0,
      },
      {
        icon: <ExclamationTriangleIcon className="h-4 w-4" />,
        label: "Overdue",
        value: stats.overdue,
        tone: "warning",
        show: stats.overdue > 0,
      },
    ],
    [pagination?.totalItems, stats]
  );

  const hasActiveFilters = searchTerm.trim() !== "" || statusFilter !== "all";

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setCurrentPage(1);
  };

  // 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("space-y-4", className)}>
      {/* Summary Stats (inline variant) */}
      {showFilters && invoices.length > 0 && (
        <SummaryStats variant="inline" items={summaryStatsItems} />
      )}

      {/* Search & Filters */}
      {showFilters && (
        <SearchFilterBar
          searchValue={searchTerm}
          onSearchChange={setSearchTerm}
          searchPlaceholder="Search by invoice number..."
          {...(!isSubscriptionMode && {
            filterValue: statusFilter,
            onFilterChange: (value: string) => {
              setStatusFilter(value as InvoiceQueryStatus | "all");
              setCurrentPage(1);
            },
            filterOptions: INVOICE_STATUS_OPTIONS,
            filterLabel: "Filter by status",
          })}
        >
          {/* Clear filters button */}
          <ClearFiltersButton onClick={clearFilters} show={hasActiveFilters} />
        </SearchFilterBar>
      )}

      {/* Invoice Table Card */}
      <div className="bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)] overflow-hidden">
        {/* 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>
    </div>
  );
}

export type { InvoicesListProps };
