import React, { useEffect, useState, useRef } from 'react';
import { Search } from 'lucide-react';
import paymentService from '../../features/payments/services/paymentService';
import type { Payment } from '../../features/payments/services/paymentService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import Pagination from '../../shared/components/Pagination';
import ExportButton from '../../shared/components/ExportButton';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { formatDate } from '../../shared/utils/format';
import { PAYMENT_STATUS } from '../../shared/constants/bookingConstants';

const PaymentManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [payments, setPayments] = useState<Payment[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    search: '',
    method: '',
    from: '',
    to: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 5;
  const abortControllerRef = useRef<AbortController | null>(null);

  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);

  useEffect(() => {
    // Cancel previous request if exists
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }

    // Create new abort controller
    abortControllerRef.current = new AbortController();

    fetchPayments();

    // Cleanup: abort request on unmount
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchPayments = async () => {
    try {
      setLoading(true);
      // Backend only supports: booking_id, status, page, limit
      // Remove search, method, from, to from API call and handle client-side
      const apiParams: { page: number; limit: number; booking_id?: number; status?: string } = {
        page: currentPage,
        limit: itemsPerPage,
      };
      
      if (filters.method) {
        // Note: Backend doesn't support method filter, will filter client-side
      }
      
      if (filters.from || filters.to) {
        // Note: Backend doesn't support date range filter, will filter client-side
      }
      
      const response = await paymentService.getPayments(apiParams);
      let paymentsList = response.data.payments || [];
      
      // Client-side filtering for search, method, and date range
      // Note: This only filters current page results
      if (filters.search) {
        paymentsList = paymentsList.filter((p) =>
          (p.transaction_id && p.transaction_id.toLowerCase().includes(filters.search.toLowerCase())) ||
          (p.booking?.booking_number && p.booking.booking_number.toLowerCase().includes(filters.search.toLowerCase())) ||
          (p.booking?.user?.name && p.booking.user.name.toLowerCase().includes(filters.search.toLowerCase())) ||
          (p.booking?.user?.email && p.booking.user.email.toLowerCase().includes(filters.search.toLowerCase()))
        );
      }
      
      if (filters.method) {
        paymentsList = paymentsList.filter((p) => p.payment_method === filters.method);
      }
      
      // Filter by payment status if needed
      if (filters.status) {
        paymentsList = paymentsList.filter((p) => p.payment_status === filters.status);
      }
      
      if (filters.from) {
        const fromDate = new Date(filters.from);
        paymentsList = paymentsList.filter((p) => {
          const paymentDate = p.payment_date ? new Date(p.payment_date) : (p.createdAt ? new Date(p.createdAt) : null);
          return paymentDate && paymentDate >= fromDate;
        });
      }
      
      if (filters.to) {
        const toDate = new Date(filters.to);
        toDate.setHours(23, 59, 59, 999); // Include entire day
        paymentsList = paymentsList.filter((p) => {
          const paymentDate = p.payment_date ? new Date(p.payment_date) : (p.createdAt ? new Date(p.createdAt) : null);
          return paymentDate && paymentDate <= toDate;
        });
      }
      
      setPayments(paymentsList);
      if (response.data.pagination) {
        // Only update pagination if not filtering (to avoid incorrect counts)
        if (!filters.search && !filters.method && !filters.from && !filters.to) {
          setTotalPages(response.data.pagination.totalPages);
          setTotalItems(response.data.pagination.total);
        } else {
          // Keep original pagination when filtering
          setTotalPages(response.data.pagination.totalPages);
          setTotalItems(response.data.pagination.total);
        }
      }
    } catch (error: unknown) {
      // Handle AbortError silently
      const isAbortError = (e: unknown): boolean => {
        return typeof e === 'object' && e !== null && (e as { name?: string }).name === 'AbortError';
      };
      if (isAbortError(error)) {
        return;
      }
      logger.error('Error fetching payments', error);
      toast.error(getUserFriendlyError(error) || 'Unable to load payments list');
    } finally {
      setLoading(false);
    }
  };

  const getMethodBadge = (method: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      cash: { 
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50', 
        text: 'text-emerald-800', 
        label: 'Cash',
        border: 'border-emerald-200'
      },
      bank_transfer: { 
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50', 
        text: 'text-blue-800', 
        label: 'Bank transfer',
        border: 'border-blue-200'
      },
      stripe: { 
        bg: 'bg-gradient-to-r from-indigo-50 to-purple-50', 
        text: 'text-indigo-800', 
        label: 'Stripe',
        border: 'border-indigo-200'
      },
      paypal: { 
        bg: 'bg-gradient-to-r from-blue-50 to-cyan-50', 
        text: 'text-blue-800', 
        label: 'PayPal',
        border: 'border-blue-200'
      },
      credit_card: { 
        bg: 'bg-gradient-to-r from-purple-50 to-pink-50', 
        text: 'text-purple-800', 
        label: 'Credit card',
        border: 'border-purple-200'
      },
    };
    const badge = badges[method] || badges.cash;
    return (
      <span className={`px-4 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  const getPaymentStatusBadge = (status: string) => {
    const statusConfig: Record<string, { bg: string; text: string; label: string; border: string }> = {
      [PAYMENT_STATUS.PAID]: {
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50',
        text: 'text-emerald-800',
        label: '✅ Paid',
        border: 'border-emerald-200'
      },
      pending: {
        bg: 'bg-gradient-to-r from-amber-50 to-yellow-50',
        text: 'text-amber-800',
        label: '⏳ Pending',
        border: 'border-amber-200'
      },
      failed: {
        bg: 'bg-gradient-to-r from-rose-50 to-red-50',
        text: 'text-rose-800',
        label: '❌ Failed',
        border: 'border-rose-200'
      },
      [PAYMENT_STATUS.REFUNDED]: {
        bg: 'bg-gradient-to-r from-slate-50 to-gray-50',
        text: 'text-slate-700',
        label: '💰 Refunded',
        border: 'border-slate-200'
      },
      completed: { // Legacy support
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50',
        text: 'text-emerald-800',
        label: '✅ Paid',
        border: 'border-emerald-200'
      },
    };
    const config = statusConfig[status] || statusConfig.pending;
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${config.bg} ${config.text} ${config.border}`}>
        {config.label}
      </span>
    );
  };

  if (loading) {
    return <Loading />;
  }

  return (
    <div className="space-y-8 bg-gradient-to-br from-slate-50 via-white to-slate-50 min-h-screen -m-6 p-8">
      {}
      <div className="animate-fade-in">
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-2">
          <div>
            <div className="flex items-center gap-3 mb-2">
              <div className="h-1 w-16 bg-gradient-to-r from-amber-400 to-amber-600 rounded-full"></div>
              <h1 className="text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
                Payment Management
              </h1>
            </div>
            <p className="text-slate-600 mt-3 text-lg font-light">Track payment transactions</p>
          </div>
          <ExportButton
            data={payments.map(p => ({
              'Transaction ID': p.transaction_id || `PAY-${p.id}`,
              'Booking Number': p.booking?.booking_number || 'N/A',
              'Customer': p.booking?.user?.name || p.booking?.user?.email || 'N/A',
              'Payment Method': p.payment_method || 'N/A',
              'Payment Type': p.payment_type || 'N/A',
              'Amount': formatCurrency(p.amount || 0),
              'Status': p.payment_status,
              'Payment Date': p.payment_date ? formatDate(p.payment_date) : 'N/A',
              'Created At': p.createdAt ? formatDate(p.createdAt) : ('created_at' in p && typeof (p as { created_at?: string }).created_at === 'string') ? formatDate((p as { created_at: string }).created_at) : 'N/A'
            }))}
            filename="payments"
            title="Payment Transactions Report"
            customHeaders={{
              'Transaction ID': 'Transaction ID',
              'Booking Number': 'Booking Number',
              'Customer': 'Customer',
              'Payment Method': 'Payment Method',
              'Payment Type': 'Payment Type',
              'Amount': 'Amount',
              'Status': 'Status',
              'Payment Date': 'Payment Date',
              'Created At': 'Created At'
            }}
          />
        </div>
      </div>

      {}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in" style={{ animationDelay: '0.1s' }}>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-5">
          <div className="relative group">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400 w-5 h-5 group-focus-within:text-amber-500 transition-colors" />
            <input
              type="text"
              placeholder="Search..."
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              className="w-full pl-12 pr-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 placeholder-slate-400 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <select
            value={filters.method}
            onChange={(e) => setFilters({ ...filters, method: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
          >
            <option value="">All methods</option>
            <option value="cash">Cash</option>
            <option value="stripe">Stripe</option>
            <option value="credit_card">Credit card</option>
          </select>
          <input
            type="date"
            value={filters.from}
            onChange={(e) => setFilters({ ...filters, from: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md"
            placeholder="From date"
          />
          <input
            type="date"
            value={filters.to}
            onChange={(e) => setFilters({ ...filters, to: e.target.value })}
            className="px-4 py-3.5 bg-white border-2 border-slate-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md"
            placeholder="To date"
          />
        </div>
      </div>

      {}
      <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 overflow-hidden animate-fade-in" style={{ animationDelay: '0.2s' }}>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900">
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Transaction ID</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Booking Number</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Customer</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Method</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Type</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Status</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Amount</th>
                <th className="px-8 py-5 text-left text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">Payment Date</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-100">
              {payments.map((payment, index) => (
                <tr 
                  key={payment.id} 
                  className="hover:bg-gradient-to-r hover:from-amber-50/30 hover:to-yellow-50/30 transition-all duration-200 group border-b border-slate-100"
                  style={{ animationDelay: `${index * 0.05}s` }}
                >
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-bold text-slate-900 font-mono">{payment.transaction_id || `PAY-${payment.id}`}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-semibold text-amber-600">{payment.booking?.booking_number}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-medium text-slate-900">{payment.booking?.user?.name}</div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getMethodBadge(payment.payment_method)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {payment.payment_type === 'deposit' ? (
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-100 text-amber-800 border border-amber-200">
                        Deposit (20%)
                      </span>
                    ) : payment.payment_type === 'remaining' ? (
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-800 border border-blue-200">
                        Remaining
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800 border border-green-200">
                        Full Payment
                      </span>
                    )}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    {getPaymentStatusBadge(payment.payment_status)}
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent">
                      {formatCurrency(payment.amount)}
                    </div>
                  </td>
                  <td className="px-8 py-5 whitespace-nowrap">
                    <div className="text-sm text-slate-600">
                      {new Date(payment.payment_date || payment.createdAt || '').toLocaleDateString('en-US')}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
          totalItems={totalItems}
          itemsPerPage={itemsPerPage}
        />
      </div>

      {}
      <div className="bg-gradient-to-r from-amber-500 via-amber-600 to-amber-700 rounded-2xl shadow-2xl p-8 text-white animate-fade-in" style={{ animationDelay: '0.3s' }}>
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-semibold mb-2 text-amber-100">Total Revenue</h3>
            <p className="text-4xl font-bold">
              {formatCurrency(payments
                .filter(p => p.payment_status === PAYMENT_STATUS.PAID || p.payment_status === 'completed')
                .reduce((sum, p) => sum + p.amount, 0))}
            </p>
            <p className="text-sm mt-3 text-amber-100/90">
              Total {payments.filter(p => p.payment_status === PAYMENT_STATUS.PAID || p.payment_status === 'completed').length} paid transaction{payments.filter(p => p.payment_status === PAYMENT_STATUS.PAID || p.payment_status === 'completed').length !== 1 ? 's' : ''}
            </p>
          </div>
          <div className="bg-white/20 backdrop-blur-sm p-6 rounded-2xl">
            <div className="text-5xl font-bold text-white/80">{payments.filter(p => p.payment_status === PAYMENT_STATUS.PAID || p.payment_status === 'completed').length}</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PaymentManagementPage;
