import React, { useEffect, useState } from 'react';
import { Search, Plus, Edit, Trash2, Eye, FileText, Filter } from 'lucide-react';
import invoiceService, { Invoice } from '../../features/payments/services/invoiceService';
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 { useNavigate } from 'react-router-dom';
import { formatDate } from '../../shared/utils/format';

const InvoiceManagementPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const navigate = useNavigate();
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    search: '',
    status: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 10;

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

  useEffect(() => {
    fetchInvoices();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters, currentPage]);

  const fetchInvoices = async () => {
    try {
      setLoading(true);
      const response = await invoiceService.getInvoices({
        status: filters.status || undefined,
        page: currentPage,
        limit: itemsPerPage,
      });
      
      if (response.status === 'success' && response.data) {
        let invoiceList = response.data.invoices || [];
        
        // Client-side filtering for search (only on current page results)
        // Note: This is a limitation - search only works on current page
        // For full search functionality, backend needs to support search parameter
        if (filters.search) {
          invoiceList = invoiceList.filter((inv) =>
            inv.invoice_number.toLowerCase().includes(filters.search.toLowerCase()) ||
            inv.customer_name.toLowerCase().includes(filters.search.toLowerCase()) ||
            inv.customer_email.toLowerCase().includes(filters.search.toLowerCase()) ||
            (inv.promotion_code && inv.promotion_code.toLowerCase().includes(filters.search.toLowerCase()))
          );
        }
        
        setInvoices(invoiceList);
        // Only update pagination if not searching (to avoid incorrect counts)
        if (!filters.search) {
          setTotalPages(response.data.total_pages || 1);
          setTotalItems(response.data.total || 0);
        } else {
          // When searching, keep original pagination but show filtered count
          setTotalPages(response.data.total_pages || 1);
          setTotalItems(response.data.total || 0);
        }
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load invoices');
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      draft: { 
        bg: 'bg-gradient-to-r from-slate-50 to-gray-50', 
        text: 'text-slate-700', 
        label: 'Draft',
        border: 'border-slate-200'
      },
      sent: { 
        bg: 'bg-gradient-to-r from-blue-50 to-indigo-50', 
        text: 'text-blue-800', 
        label: 'Sent',
        border: 'border-blue-200'
      },
      paid: { 
        bg: 'bg-gradient-to-r from-emerald-50 to-green-50', 
        text: 'text-emerald-800', 
        label: 'Paid',
        border: 'border-emerald-200'
      },
      overdue: { 
        bg: 'bg-gradient-to-r from-rose-50 to-red-50', 
        text: 'text-rose-800', 
        label: 'Overdue',
        border: 'border-rose-200'
      },
      cancelled: { 
        bg: 'bg-gradient-to-r from-slate-50 to-gray-50', 
        text: 'text-slate-700', 
        label: 'Cancelled',
        border: 'border-slate-200'
      },
    };
    return badges[status] || badges.draft;
  };

  const handleDelete = async (id: number) => {
    if (!window.confirm('Are you sure you want to delete this invoice?')) {
      return;
    }

    try {
      await invoiceService.deleteInvoice(id);
      toast.success('Invoice deleted successfully');
      fetchInvoices();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to delete invoice');
    }
  };

  if (loading && invoices.length === 0) {
    return <Loading fullScreen text="Loading invoices..." />;
  }

  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="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 animate-fade-in">
        <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">
              Invoice Management
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Manage and track all invoices</p>
        </div>
        <div className="flex gap-3 items-center">
          <ExportButton
            data={invoices.map(i => ({
              'Invoice Number': i.invoice_number,
              'Customer Name': i.customer_name,
              'Customer Email': i.customer_email,
              'Booking ID': i.booking_id || 'N/A',
              'Subtotal': formatCurrency(i.subtotal),
              'Tax Amount': formatCurrency(i.tax_amount),
              'Discount Amount': formatCurrency(i.discount_amount),
              'Total Amount': formatCurrency(i.total_amount),
              'Amount Paid': formatCurrency(i.amount_paid),
              'Balance Due': formatCurrency(i.balance_due),
              'Status': i.status,
              'Issue Date': i.issue_date ? formatDate(i.issue_date) : 'N/A',
              'Due Date': i.due_date ? formatDate(i.due_date) : 'N/A',
              'Paid Date': i.paid_date ? formatDate(i.paid_date) : 'N/A',
              'Is Proforma': i.is_proforma ? 'Yes' : 'No'
            }))}
            filename="invoices"
            title="Invoice Management Report"
          />
          <button
            onClick={() => navigate('/admin/bookings')}
            className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white rounded-xl font-semibold hover:from-amber-600 hover:to-amber-700 transition-all duration-200 shadow-lg hover:shadow-xl"
          >
            <Plus className="w-5 h-5" />
            Create Invoice from Booking
          </button>
        </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-3 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 invoices..."
              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.status}
            onChange={(e) => setFilters({ ...filters, status: 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 Statuses</option>
            <option value="draft">Draft</option>
            <option value="sent">Sent</option>
            <option value="paid">Paid</option>
            <option value="overdue">Overdue</option>
            <option value="cancelled">Cancelled</option>
          </select>
          <div className="flex items-center gap-3 px-4 py-3.5 bg-gradient-to-r from-slate-50 to-white border-2 border-slate-200 rounded-xl">
            <Filter className="w-5 h-5 text-amber-600" />
            <span className="text-sm font-semibold text-slate-700">
              {totalItems} invoice{totalItems !== 1 ? 's' : ''}
            </span>
          </div>
        </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">
                  Invoice #
                </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">
                  Booking
                </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">
                  Promotion
                </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">
                  Due Date
                </th>
                <th className="px-8 py-5 text-right text-xs font-bold text-amber-100 uppercase tracking-wider border-b border-slate-700">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-slate-100">
              {invoices.length > 0 ? (
                invoices.map((invoice, index) => {
                  const statusBadge = getStatusBadge(invoice.status);
                  return (
                    <tr 
                      key={invoice.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="flex items-center">
                          <FileText className="w-5 h-5 text-amber-600 mr-3" />
                          <span className="text-sm font-bold text-slate-900 font-mono">
                            {invoice.invoice_number}
                          </span>
                        </div>
                      </td>
                      <td className="px-8 py-5">
                        <div className="text-sm font-semibold text-slate-900">{invoice.customer_name}</div>
                        <div className="text-sm text-slate-500">{invoice.customer_email}</div>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        <span className="text-sm font-medium text-amber-600">#{invoice.booking_id}</span>
                      </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(invoice.total_amount)}
                        </div>
                        {invoice.balance_due > 0 && (
                          <div className="text-xs text-rose-600 font-medium mt-1">
                            Due: {formatCurrency(invoice.balance_due)}
                          </div>
                        )}
                        {invoice.discount_amount > 0 && (
                          <div className="text-xs text-green-600 font-medium mt-1">
                            Discount: -{formatCurrency(invoice.discount_amount)}
                          </div>
                        )}
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        {invoice.promotion_code ? (
                          <span className="px-3 py-1 text-xs font-semibold rounded-full bg-gradient-to-r from-purple-50 to-pink-50 text-purple-700 border border-purple-200">
                            {invoice.promotion_code}
                          </span>
                        ) : (
                          <span className="text-xs text-slate-400">—</span>
                        )}
                        {invoice.is_proforma && (
                          <div className="text-xs text-blue-600 font-medium mt-1">
                            Proforma
                          </div>
                        )}
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap">
                        <span className={`px-4 py-1.5 text-xs font-semibold rounded-full border shadow-sm ${statusBadge.bg} ${statusBadge.text} ${statusBadge.border || ''}`}>
                          {statusBadge.label}
                        </span>
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap text-sm text-slate-600">
                        {formatDate(invoice.due_date, 'short')}
                      </td>
                      <td className="px-8 py-5 whitespace-nowrap text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => navigate(`/admin/invoices/${invoice.id}`)}
                            className="p-2 rounded-lg text-blue-600 hover:text-blue-700 hover:bg-blue-50 transition-all duration-200 shadow-sm hover:shadow-md border border-blue-200 hover:border-blue-300"
                            title="View"
                          >
                            <Eye className="w-5 h-5" />
                          </button>
                          <button
                            onClick={() => navigate(`/admin/invoices/${invoice.id}/edit`)}
                            className="p-2 rounded-lg text-indigo-600 hover:text-indigo-700 hover:bg-indigo-50 transition-all duration-200 shadow-sm hover:shadow-md border border-indigo-200 hover:border-indigo-300"
                            title="Edit"
                          >
                            <Edit className="w-5 h-5" />
                          </button>
                          <button
                            onClick={() => handleDelete(invoice.id)}
                            className="p-2 rounded-lg text-rose-600 hover:text-rose-700 hover:bg-rose-50 transition-all duration-200 shadow-sm hover:shadow-md border border-rose-200 hover:border-rose-300"
                            title="Delete"
                          >
                            <Trash2 className="w-5 h-5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr>
                  <td colSpan={8} className="px-8 py-12 text-center">
                    <div className="text-slate-500">
                      <FileText className="w-16 h-16 mx-auto mb-4 text-slate-300" />
                      <p className="text-lg font-semibold">No invoices found</p>
                      <p className="text-sm mt-1">Create your first invoice to get started</p>
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {}
        {totalPages > 1 && (
          <div className="px-6 py-4 border-t border-gray-200">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default InvoiceManagementPage;
