import React, { useEffect, useState } from 'react';
import { 
  BarChart3, 
  CreditCard,
  Receipt,
  TrendingUp,
  RefreshCw,
  DollarSign,
  FileText,
  Calendar,
  AlertCircle
} from 'lucide-react';
import { reportService, ReportData, paymentService, invoiceService } from '../../services/api';
import type { Payment } from '../../services/api/paymentService';
import type { Invoice } from '../../services/api/invoiceService';
import { toast } from 'react-toastify';
import { Loading, EmptyState, ExportButton } from '../../components/common';
import CurrencyIcon from '../../components/common/CurrencyIcon';
import { formatDate } from '../../utils/format';
import { useFormatCurrency } from '../../hooks/useFormatCurrency';
import { useAsync } from '../../hooks/useAsync';
import { useNavigate } from 'react-router-dom';

const AccountantDashboardPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const navigate = useNavigate();
  const [dateRange, setDateRange] = useState({
    from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
  });
  const [recentPayments, setRecentPayments] = useState<Payment[]>([]);
  const [recentInvoices, setRecentInvoices] = useState<Invoice[]>([]);
  const [loadingPayments, setLoadingPayments] = useState(false);
  const [loadingInvoices, setLoadingInvoices] = useState(false);
  const [financialSummary, setFinancialSummary] = useState({
    totalRevenue: 0,
    totalPayments: 0,
    totalInvoices: 0,
    pendingPayments: 0,
    overdueInvoices: 0,
    paidInvoices: 0,
  });
  
  const fetchDashboardData = async () => {
    const response = await reportService.getReports({
      from: dateRange.from,
      to: dateRange.to,
    });
    return response.data;
  };

  const { data: stats, loading, error, execute } = useAsync<ReportData>(
    fetchDashboardData,
    {
      immediate: true,
      onError: (error: any) => {
        toast.error(error.message || 'Unable to load dashboard data');
      }
    }
  );

  useEffect(() => {
    execute();
  }, [dateRange]); 

  useEffect(() => {
    const fetchPayments = async () => {
      try {
        setLoadingPayments(true);
        const response = await paymentService.getPayments({ page: 1, limit: 10 });
        if (response.success && response.data?.payments) {
          setRecentPayments(response.data.payments);
          // Calculate financial summary
          const completedPayments = response.data.payments.filter((p: Payment) => p.payment_status === 'completed');
          const pendingPayments = response.data.payments.filter((p: Payment) => p.payment_status === 'pending');
          const totalRevenue = completedPayments.reduce((sum: number, p: Payment) => sum + (p.amount || 0), 0);
          
          setFinancialSummary(prev => ({
            ...prev,
            totalRevenue,
            totalPayments: response.data.payments.length,
            pendingPayments: pendingPayments.length,
          }));
        }
      } catch (err: any) {
        console.error('Error fetching payments:', err);
      } finally {
        setLoadingPayments(false);
      }
    };
    fetchPayments();
  }, []);

  useEffect(() => {
    const fetchInvoices = async () => {
      try {
        setLoadingInvoices(true);
        const response = await invoiceService.getInvoices({ page: 1, limit: 10 });
        if (response.status === 'success' && response.data?.invoices) {
          setRecentInvoices(response.data.invoices);
          // Calculate invoice summary
          const paidInvoices = response.data.invoices.filter((inv: Invoice) => inv.status === 'paid');
          const overdueInvoices = response.data.invoices.filter((inv: Invoice) => inv.status === 'overdue');
          
          setFinancialSummary(prev => ({
            ...prev,
            totalInvoices: response.data.invoices.length,
            paidInvoices: paidInvoices.length,
            overdueInvoices: overdueInvoices.length,
          }));
        }
      } catch (err: any) {
        console.error('Error fetching invoices:', err);
      } finally {
        setLoadingInvoices(false);
      }
    };
    fetchInvoices();
  }, []);

  const handleRefresh = () => {
    execute();
  };

  const getPaymentStatusColor = (status: string) => {
    switch (status) {
      case 'completed':
        return 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200';
      case 'pending':
        return 'bg-gradient-to-r from-amber-50 to-yellow-50 text-amber-800 border-amber-200';
      case 'failed':
        return 'bg-gradient-to-r from-rose-50 to-red-50 text-rose-800 border-rose-200';
      case 'refunded':
        return 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200';
      default:
        return 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200';
    }
  };

  const getInvoiceStatusColor = (status: string) => {
    switch (status) {
      case 'paid':
        return 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200';
      case 'sent':
        return 'bg-gradient-to-r from-blue-50 to-indigo-50 text-blue-800 border-blue-200';
      case 'overdue':
        return 'bg-gradient-to-r from-rose-50 to-red-50 text-rose-800 border-rose-200';
      case 'draft':
        return 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200';
      default:
        return 'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200';
    }
  };

  if (loading) {
    return <Loading fullScreen text="Loading dashboard..." />;
  }

  if (error || !stats) {
    return (
      <div className="space-y-6">
        <EmptyState
          title="Unable to Load Dashboard"
          description={error?.message || 'Something went wrong. Please try again.'}
          action={{
            label: 'Retry',
            onClick: handleRefresh
          }}
        />
      </div>
    );
  }

  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">
      {/* Header */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-6 animate-fade-in">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="h-1 w-16 bg-gradient-to-r from-emerald-400 to-emerald-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">
              Financial Dashboard
            </h1>
          </div>
          <p className="text-slate-600 mt-3 text-lg font-light">Comprehensive financial overview and analytics</p>
        </div>
        
        {/* Date Range & Actions */}
        <div className="flex flex-col sm:flex-row gap-3 items-start sm:items-center">
          <div className="flex gap-3 items-center">
            <input
              type="date"
              value={dateRange.from}
              onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
              className="px-4 py-2.5 bg-white border-2 border-slate-200 rounded-xl focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md"
            />
            <span className="text-slate-500 font-medium">to</span>
            <input
              type="date"
              value={dateRange.to}
              onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
              className="px-4 py-2.5 bg-white border-2 border-slate-200 rounded-xl focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md"
            />
          </div>
          <div className="flex gap-3 items-center">
            <ExportButton
              data={[
                {
                  'Total Revenue': formatCurrency(stats?.total_revenue || 0),
                  'Total Payments': stats?.total_payments || 0,
                  'Total Invoices': stats?.total_invoices || 0,
                  'Total Customers': stats?.total_customers || 0,
                  'Available Rooms': stats?.available_rooms || 0,
                  'Occupied Rooms': stats?.occupied_rooms || 0,
                  'Pending Payments': financialSummary.pendingPayments,
                  'Overdue Invoices': financialSummary.overdueInvoices,
                  'Date Range': `${dateRange.from} to ${dateRange.to}`
                },
                ...(recentPayments.map(p => ({
                  'Type': 'Payment',
                  'Transaction ID': p.transaction_id || `PAY-${p.id}`,
                  'Amount': formatCurrency(p.amount || 0),
                  'Status': p.payment_status,
                  'Method': p.payment_method,
                  'Date': p.payment_date ? formatDate(p.payment_date) : 'N/A',
                  'Booking': p.booking?.booking_number || 'N/A'
                }))),
                ...(recentInvoices.map(i => ({
                  'Type': 'Invoice',
                  'Invoice Number': i.invoice_number,
                  'Customer': i.customer_name,
                  'Total Amount': formatCurrency(i.total_amount),
                  'Amount Due': formatCurrency(i.amount_due),
                  'Status': i.status,
                  'Due Date': i.due_date ? formatDate(i.due_date) : 'N/A',
                  'Issue Date': i.issue_date ? formatDate(i.issue_date) : 'N/A'
                })))
              ]}
              filename="accountant-dashboard"
              title="Accountant Financial Dashboard Report"
            />
            <button
              onClick={handleRefresh}
              disabled={loading}
              className="px-6 py-2.5 bg-gradient-to-r from-emerald-500 to-emerald-600 text-white rounded-xl font-semibold hover:from-emerald-600 hover:to-emerald-700 transition-all duration-200 shadow-lg hover:shadow-xl disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 text-sm"
            >
              <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
              Refresh
            </button>
          </div>
        </div>
      </div>

      {/* Financial Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {/* Total Revenue */}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 border-l-4 border-l-emerald-500 animate-slide-up hover:shadow-2xl transition-all duration-300">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Total Revenue</p>
              <p className="text-3xl font-bold bg-gradient-to-r from-emerald-600 to-emerald-700 bg-clip-text text-transparent">
                {formatCurrency(financialSummary.totalRevenue || stats?.total_revenue || 0)}
              </p>
            </div>
            <div className="bg-gradient-to-br from-emerald-100 to-emerald-200 p-4 rounded-2xl shadow-lg">
              <DollarSign className="w-7 h-7 text-emerald-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <TrendingUp className="w-4 h-4 text-emerald-500 mr-2" />
            <span className="text-emerald-600 font-semibold text-sm">Active</span>
            <span className="text-slate-500 ml-2 text-sm">All time revenue</span>
          </div>
        </div>

        {/* Total Payments */}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 border-l-4 border-l-blue-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.1s' }}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Total Payments</p>
              <p className="text-3xl font-bold bg-gradient-to-r from-blue-600 to-blue-700 bg-clip-text text-transparent">
                {financialSummary.totalPayments}
              </p>
            </div>
            <div className="bg-gradient-to-br from-blue-100 to-blue-200 p-4 rounded-2xl shadow-lg">
              <CreditCard className="w-7 h-7 text-blue-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-sm">
              {financialSummary.pendingPayments} pending payments
            </span>
          </div>
        </div>

        {/* Total Invoices */}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 border-l-4 border-l-purple-500 animate-slide-up hover:shadow-2xl transition-all duration-300" style={{ animationDelay: '0.2s' }}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-slate-500 text-xs font-semibold uppercase tracking-wider mb-2">Total Invoices</p>
              <p className="text-3xl font-bold bg-gradient-to-r from-purple-600 to-purple-700 bg-clip-text text-transparent">
                {financialSummary.totalInvoices}
              </p>
            </div>
            <div className="bg-gradient-to-br from-purple-100 to-purple-200 p-4 rounded-2xl shadow-lg">
              <Receipt className="w-7 h-7 text-purple-600" />
            </div>
          </div>
          <div className="flex items-center mt-5 pt-4 border-t border-slate-100">
            <span className="text-slate-500 text-sm">
              {financialSummary.paidInvoices} paid • {financialSummary.overdueInvoices} overdue
            </span>
          </div>
        </div>
      </div>

      {/* Recent Payments and Invoices */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Payments */}
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
          <div className="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
            <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
              <CreditCard className="w-5 h-5 text-emerald-600" />
              Recent Payments
            </h2>
            <button
              onClick={() => navigate('/accountant/payments')}
              className="text-sm text-emerald-600 hover:text-emerald-700 font-semibold hover:underline transition-colors"
            >
              View All →
            </button>
          </div>
          {loadingPayments ? (
            <div className="flex items-center justify-center py-8">
              <Loading text="Loading payments..." />
            </div>
          ) : recentPayments && recentPayments.length > 0 ? (
            <div className="space-y-3">
              {recentPayments.slice(0, 5).map((payment) => (
                <div 
                  key={payment.id}
                  className="flex items-center justify-between p-4 bg-gradient-to-r from-slate-50 to-white rounded-xl hover:from-emerald-50 hover:to-yellow-50 border border-slate-200 hover:border-emerald-300 hover:shadow-lg cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/accountant/payments`)}
                >
                  <div className="flex items-center space-x-4 flex-1">
                    <div className="p-3 bg-gradient-to-br from-blue-100 to-blue-200 rounded-xl shadow-md">
                      <CreditCard className="w-5 h-5 text-blue-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-slate-900 truncate text-lg">
                        {formatCurrency(payment.amount)}
                      </p>
                      <div className="flex items-center gap-2 mt-1">
                        <p className="text-sm text-slate-600 font-medium">
                          {payment.payment_method || 'N/A'}
                        </p>
                        {payment.payment_date && (
                          <span className="text-xs text-slate-400">
                            • {formatDate(payment.payment_date, 'short')}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  <span className={`px-3 py-1.5 text-xs font-semibold rounded-full border shadow-sm ${getPaymentStatusColor(payment.payment_status)}`}>
                    {payment.payment_status.charAt(0).toUpperCase() + payment.payment_status.slice(1)}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Recent Payments"
              description="Recent payment transactions will appear here"
              action={{
                label: 'View All Payments',
                onClick: () => navigate('/accountant/payments')
              }}
            />
          )}
        </div>

        {/* Recent Invoices */}
        <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.2s' }}>
          <div className="flex items-center justify-between mb-6 pb-4 border-b border-slate-200">
            <h2 className="text-xl font-bold text-slate-900 flex items-center gap-2">
              <Receipt className="w-5 h-5 text-purple-600" />
              Recent Invoices
            </h2>
            <button
              onClick={() => navigate('/accountant/invoices')}
              className="text-sm text-emerald-600 hover:text-emerald-700 font-semibold hover:underline transition-colors"
            >
              View All →
            </button>
          </div>
          {loadingInvoices ? (
            <div className="flex items-center justify-center py-8">
              <Loading text="Loading invoices..." />
            </div>
          ) : recentInvoices && recentInvoices.length > 0 ? (
            <div className="space-y-3">
              {recentInvoices.slice(0, 5).map((invoice) => (
                <div 
                  key={invoice.id}
                  className="flex items-center justify-between p-4 bg-gradient-to-r from-slate-50 to-white rounded-xl hover:from-purple-50 hover:to-indigo-50 border border-slate-200 hover:border-purple-300 hover:shadow-lg cursor-pointer transition-all duration-200"
                  onClick={() => navigate(`/accountant/invoices`)}
                >
                  <div className="flex items-center space-x-4 flex-1">
                    <div className="p-3 bg-gradient-to-br from-purple-100 to-purple-200 rounded-xl shadow-md">
                      <Receipt className="w-5 h-5 text-purple-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-slate-900 truncate text-lg">
                        {invoice.invoice_number}
                      </p>
                      <div className="flex items-center gap-2 mt-1">
                        <p className="text-sm text-slate-600 font-medium">
                          {formatCurrency(invoice.total_amount || 0)}
                        </p>
                        {invoice.issue_date && (
                          <span className="text-xs text-slate-400">
                            • {formatDate(invoice.issue_date, 'short')}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                  <span className={`px-3 py-1.5 text-xs font-semibold rounded-full border shadow-sm ${getInvoiceStatusColor(invoice.status)}`}>
                    {invoice.status.charAt(0).toUpperCase() + invoice.status.slice(1)}
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState
              title="No Recent Invoices"
              description="Recent invoices will appear here"
              action={{
                label: 'View All Invoices',
                onClick: () => navigate('/accountant/invoices')
              }}
            />
          )}
        </div>
      </div>

      {/* Alerts Section */}
      {(financialSummary.overdueInvoices > 0 || financialSummary.pendingPayments > 0) && (
        <div className="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-slate-200/60 p-6 animate-fade-in">
          <div className="flex items-center gap-3 mb-4">
            <AlertCircle className="w-5 h-5 text-amber-600" />
            <h2 className="text-xl font-bold text-slate-900">Financial Alerts</h2>
          </div>
          <div className="space-y-3">
            {financialSummary.overdueInvoices > 0 && (
              <div className="p-4 bg-gradient-to-r from-rose-50 to-red-50 rounded-xl border border-rose-200">
                <p className="text-rose-800 font-semibold">
                  ⚠️ {financialSummary.overdueInvoices} overdue invoice{financialSummary.overdueInvoices !== 1 ? 's' : ''} require attention
                </p>
              </div>
            )}
            {financialSummary.pendingPayments > 0 && (
              <div className="p-4 bg-gradient-to-r from-amber-50 to-yellow-50 rounded-xl border border-amber-200">
                <p className="text-amber-800 font-semibold">
                  ⏳ {financialSummary.pendingPayments} pending payment{financialSummary.pendingPayments !== 1 ? 's' : ''} awaiting processing
                </p>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default AccountantDashboardPage;

