/**
 * InvoicesPage
 * Standalone page for viewing and managing invoices
 * Route: /billing/invoices
 * Epic: OQI-005 Pagos y Stripe
 */

import React, { useState, useCallback } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import {
  FileText,
  ArrowLeft,
  RefreshCw,
  Loader2,
  AlertCircle,
  Calendar,
  Filter,
  X,
} from 'lucide-react';
import { useInvoices, useDownloadInvoice } from '../../../hooks/usePayments';
import InvoiceList from '../../../components/payments/InvoiceList';
import InvoiceDetail from '../../../components/payments/InvoiceDetail';
import type { Invoice } from '../../../components/payments/InvoiceList';

const ITEMS_PER_PAGE = 10;

export default function InvoicesPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedInvoiceId, setSelectedInvoiceId] = useState<string | null>(
    searchParams.get('invoiceId')
  );
  const [statusFilter, setStatusFilter] = useState<'all' | 'paid' | 'pending' | 'failed'>('all');
  const [dateRange, setDateRange] = useState<{ start?: string; end?: string }>({});
  const [showFilters, setShowFilters] = useState(false);

  const offset = (currentPage - 1) * ITEMS_PER_PAGE;
  const { data, isLoading, error, refetch } = useInvoices({
    limit: ITEMS_PER_PAGE,
    offset,
  });

  const downloadInvoice = useDownloadInvoice();

  const handleInvoiceClick = useCallback((invoice: Invoice) => {
    setSelectedInvoiceId(invoice.id);
    setSearchParams({ invoiceId: invoice.id });
  }, [setSearchParams]);

  const handleCloseDetail = useCallback(() => {
    setSelectedInvoiceId(null);
    setSearchParams({});
  }, [setSearchParams]);

  const handleDownload = useCallback((invoice: Invoice) => {
    downloadInvoice.mutate(invoice.id);
  }, [downloadInvoice]);

  // Page change handler - reserved for future custom pagination
  const _handlePageChange = useCallback((page: number) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  const clearFilters = useCallback(() => {
    setStatusFilter('all');
    setDateRange({});
  }, []);

  const hasActiveFilters = statusFilter !== 'all' || dateRange.start || dateRange.end;

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            to="/billing"
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-white flex items-center gap-3">
              <div className="p-2 bg-blue-600/20 rounded-lg">
                <FileText className="w-6 h-6 text-blue-400" />
              </div>
              Invoices
            </h1>
            <p className="text-gray-400 mt-1">
              View and download your billing history
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors ${
              showFilters || hasActiveFilters
                ? 'bg-blue-600/20 text-blue-400 border border-blue-600/50'
                : 'bg-gray-800 text-gray-400 hover:text-white border border-gray-700'
            }`}
          >
            <Filter className="w-4 h-4" />
            Filters
            {hasActiveFilters && (
              <span className="w-2 h-2 bg-blue-400 rounded-full" />
            )}
          </button>
          <button
            onClick={() => refetch()}
            disabled={isLoading}
            className="flex items-center gap-2 px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-400 hover:text-white rounded-lg transition-colors border border-gray-700 disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
            Refresh
          </button>
        </div>
      </div>

      {/* Filters Panel */}
      {showFilters && (
        <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4 space-y-4">
          <div className="flex items-center justify-between">
            <h3 className="text-white font-medium">Filter Invoices</h3>
            {hasActiveFilters && (
              <button
                onClick={clearFilters}
                className="flex items-center gap-1.5 text-sm text-gray-400 hover:text-white transition-colors"
              >
                <X className="w-4 h-4" />
                Clear filters
              </button>
            )}
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {/* Status Filter */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">Status</label>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
                className="w-full bg-gray-900 border border-gray-700 rounded-lg px-3 py-2 text-white focus:border-blue-500 focus:outline-none"
              >
                <option value="all">All Statuses</option>
                <option value="paid">Paid</option>
                <option value="pending">Pending</option>
                <option value="failed">Failed</option>
              </select>
            </div>

            {/* Date Range */}
            <div>
              <label className="block text-sm text-gray-400 mb-2">From Date</label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                <input
                  type="date"
                  value={dateRange.start || ''}
                  onChange={(e) => setDateRange((prev) => ({ ...prev, start: e.target.value }))}
                  className="w-full bg-gray-900 border border-gray-700 rounded-lg pl-10 pr-3 py-2 text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm text-gray-400 mb-2">To Date</label>
              <div className="relative">
                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                <input
                  type="date"
                  value={dateRange.end || ''}
                  onChange={(e) => setDateRange((prev) => ({ ...prev, end: e.target.value }))}
                  className="w-full bg-gray-900 border border-gray-700 rounded-lg pl-10 pr-3 py-2 text-white focus:border-blue-500 focus:outline-none"
                />
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Summary Stats */}
      {data && !isLoading && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
            <p className="text-gray-400 text-sm">Total Invoices</p>
            <p className="text-2xl font-bold text-white mt-1">{data.total}</p>
          </div>
          <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
            <p className="text-gray-400 text-sm">Paid</p>
            <p className="text-2xl font-bold text-green-400 mt-1">
              {data.invoices.filter((i) => i.status === 'paid').length}
            </p>
          </div>
          <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
            <p className="text-gray-400 text-sm">Pending</p>
            <p className="text-2xl font-bold text-yellow-400 mt-1">
              {data.invoices.filter((i) => i.status === 'open' || i.status === 'draft').length}
            </p>
          </div>
          <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-4">
            <p className="text-gray-400 text-sm">Total Amount</p>
            <p className="text-2xl font-bold text-white mt-1">
              ${data.invoices.reduce((sum, i) => sum + i.amount, 0).toLocaleString('en-US', { minimumFractionDigits: 2 })}
            </p>
          </div>
        </div>
      )}

      {/* Invoice List */}
      <div className="bg-gray-800/50 border border-gray-700 rounded-xl">
        {error ? (
          <div className="text-center py-12">
            <AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-3" />
            <p className="text-gray-400 mb-4">
              {error instanceof Error ? error.message : 'Failed to load invoices'}
            </p>
            <button
              onClick={() => refetch()}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm"
            >
              Retry
            </button>
          </div>
        ) : (
          <InvoiceList
            onInvoiceClick={handleInvoiceClick}
            onDownload={handleDownload}
            itemsPerPage={ITEMS_PER_PAGE}
            showFilters={false}
            compact={false}
          />
        )}
      </div>

      {/* Invoice Detail Modal */}
      {selectedInvoiceId && (
        <InvoiceDetail
          invoiceId={selectedInvoiceId}
          onClose={handleCloseDetail}
        />
      )}

      {/* Download Loading Indicator */}
      {downloadInvoice.isPending && (
        <div className="fixed bottom-4 right-4 flex items-center gap-2 px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg shadow-xl">
          <Loader2 className="w-4 h-4 text-blue-400 animate-spin" />
          <span className="text-white text-sm">Downloading invoice...</span>
        </div>
      )}
    </div>
  );
}
