import React, { useState, useEffect } from 'react';
import { DollarSign, CreditCard, TrendingUp, PieChart, Users, AlertCircle, Check, Clock, Edit2, Save, X, Settings, Receipt, BarChart3, FileText, Upload, Building, Phone, Mail, MapPin, DollarSign as PayIcon, Calendar, Download, Filter } from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Textarea } from '@/components/ui/textarea';
import { Separator } from '@/components/ui/separator';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart as RechartsPieChart, Cell, LineChart, Line, AreaChart, Area } from 'recharts';
import { adminApi, type FinancialOverview, type FinancialTransaction, type CommissionRate } from '@/services/adminApi';
import { useToast } from '@/hooks/use-toast';

interface FinancialTabProps {
  stats: any;
  isAdmin: boolean;
  isSuperAdmin: boolean;
}

interface Settlement {
  id: string;
  merchantId: string;
  settlementPeriod: string;
  periodStart: string;
  periodEnd: string;
  totalGross: string;
  totalCommission: string;
  totalNet: string;
  transactionCount: number;
  status: 'pending' | 'processing' | 'completed';
  createdAt: string;
  merchant: {
    id: string;
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
  };
}

interface PaymentMethod {
  id: string;
  type: 'bank_transfer' | 'paypal' | 'stripe' | 'cash';
  bankName?: string;
  accountNumber?: string;
  accountHolder?: string;
  email?: string;
  details: string;
}

const FinancialTab: React.FC<FinancialTabProps> = ({ isSuperAdmin }) => {
  const [activeSection, setActiveSection] = useState('dashboard');
  const [overview, setOverview] = useState<FinancialOverview | null>(null);
  const [transactions, setTransactions] = useState<FinancialTransaction[]>([]);
  const [settlementTransactions, setSettlementTransactions] = useState<FinancialTransaction[]>([]);
  const [commissionRates, setCommissionRates] = useState<CommissionRate[]>([]);
  const [settlements, setSettlements] = useState<Settlement[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingCommission, setEditingCommission] = useState<string | null>(null);
  const [editValue, setEditValue] = useState('');
  const [period, setPeriod] = useState('month');
  const [transactionFilters, setTransactionFilters] = useState({
    status: 'all',
    serviceType: 'all',
    page: 1
  });
  const [reportFilters, setReportFilters] = useState({
    merchant: 'all',
    serviceType: 'all',
    status: 'all',
    transactionType: 'all'
  });
  const [selectedSettlement, setSelectedSettlement] = useState<Settlement | null>(null);
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
  const [merchantPaymentMethods, setMerchantPaymentMethods] = useState<PaymentMethod[]>([]);
  const [settlementProof, setSettlementProof] = useState<File | null>(null);
  const [settlementNotes, setSettlementNotes] = useState('');
  const [showSettlementModal, setShowSettlementModal] = useState(false);
  const [reportDateRange, setReportDateRange] = useState({
    startDate: '2025-01-01',
    endDate: '2025-09-30'
  });
  const { toast } = useToast();

  const menuItems = [
    { id: 'dashboard', label: 'Dashboard', icon: BarChart3 },
    { id: 'transactions', label: 'Transacciones', icon: CreditCard },
    { id: 'settlements', label: 'Liquidaciones', icon: PayIcon },
    { id: 'commissions', label: 'Comisiones', icon: Settings },
    { id: 'reports', label: 'Reportes', icon: FileText },
  ];

  // Sample data for charts
  const revenueData = [
    { month: 'Ene', revenue: 2400, commissions: 240 },
    { month: 'Feb', revenue: 1398, commissions: 140 },
    { month: 'Mar', revenue: 9800, commissions: 980 },
    { month: 'Abr', revenue: 3908, commissions: 391 },
    { month: 'May', revenue: 4800, commissions: 480 },
    { month: 'Jun', revenue: 3800, commissions: 380 },
    { month: 'Jul', revenue: 4300, commissions: 430 },
    { month: 'Ago', revenue: 2250, commissions: 200 },
  ];

  const serviceTypeData = [
    { name: 'Hotels', value: 40, color: '#F84525' },
    { name: 'Restaurantes', value: 25, color: '#FF6B35' },
    { name: 'Guías', value: 20, color: '#FFA726' },
    { name: 'Taxis', value: 10, color: '#FFD54F' },
    { name: 'Comercios', value: 5, color: '#FFEB3B' },
  ];

  const transactionTrendsData = [
    { day: 'Lun', transactions: 24 },
    { day: 'Mar', transactions: 35 },
    { day: 'Mié', transactions: 28 },
    { day: 'Jue', transactions: 42 },
    { day: 'Vie', transactions: 38 },
    { day: 'Sáb', transactions: 55 },
    { day: 'Dom', transactions: 32 },
  ];

  const COLORS = ['#F84525', '#FF6B35', '#FFA726', '#FFD54F', '#FFEB3B'];

  useEffect(() => {
    loadFinancialData();
  }, [period]);

  useEffect(() => {
    if (activeSection === 'transactions') {
      loadTransactions();
    } else if (activeSection === 'settlements') {
      loadSettlements();
    }
  }, [transactionFilters, activeSection]);

  const loadFinancialData = async () => {
    try {
      setLoading(true);
      const [overviewData, commissionsData] = await Promise.all([
        adminApi.getFinancialOverview(period),
        adminApi.getCommissionRates()
      ]);
      
      setOverview(overviewData as FinancialOverview);
      setCommissionRates(commissionsData as CommissionRate[]);
    } catch (error: any) {
      console.error('Error loading financial data:', error);
      toast({
        title: 'Error',
        description: 'No se pudo cargar la información financiera',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const loadTransactions = async () => {
    try {
      const response = await adminApi.getFinancialTransactions(
        transactionFilters.page,
        20,
        transactionFilters.status === 'all' ? undefined : transactionFilters.status,
        transactionFilters.serviceType === 'all' ? undefined : transactionFilters.serviceType
      );
      setTransactions((response as any).data || []);
    } catch (error: any) {
      console.error('Error loading transactions:', error);
    }
  };

  const loadSettlements = async () => {
    try {
      const response = await adminApi.getPendingSettlements();
      setSettlements(response as Settlement[]);
    } catch (error: any) {
      console.error('Error loading settlements:', error);
    }
  };

  const loadMerchantPaymentMethods = async (merchantId: string) => {
    try {
      const response = await adminApi.getMerchantPaymentMethods(merchantId);
      setPaymentMethods(response as PaymentMethod[]);
    } catch (error: any) {
      console.error('Error loading payment methods:', error);
      // Mock data for demonstration
      setPaymentMethods([
        {
          id: '1',
          type: 'bank_transfer',
          bankName: 'Banco Popular',
          accountNumber: '****1234',
          accountHolder: 'Juan Pérez',
          details: 'Cuenta Corriente - Banco Popular'
        },
        {
          id: '2',
          type: 'paypal',
          email: 'comercio@example.com',
          details: 'PayPal - comercio@example.com'
        }
      ]);
    }
  };

  const loadSettlementTransactions = async (settlement: Settlement) => {
    try {
      // Try direct endpoint first
      const response = await adminApi.getSettlementTransactions(settlement.id).catch(() => [] as any);
      let items = (response as any) as FinancialTransaction[];

      // Fallback: fetch generic transactions and filter by merchant/date/status
      if (!items || items.length === 0) {
        const txPage = await adminApi.getFinancialTransactions(1, 100, 'settled');
        const start = new Date(settlement.periodStart).getTime();
        const end = new Date(settlement.periodEnd).getTime();
        items = (txPage as any).transactions
          ? (txPage as any).transactions as FinancialTransaction[]
          : (txPage as any as FinancialTransaction[]);
        items = items.filter(t => {
          const ts = new Date(t.createdAt).getTime();
          return t.merchantId === settlement.merchantId && ts >= start && ts <= end && t.status === 'settled';
        });
      }

      setSettlementTransactions(items);
    } catch (error: any) {
      console.error('Error loading settlement transactions:', error);
      setSettlementTransactions([]);
    }
  };
  const updateCommissionRate = async (serviceType: string, newRate: number) => {
    try {
      await adminApi.updateCommissionRate(serviceType, newRate);
      
      setCommissionRates(prev => 
        prev.map(rate => 
          rate.serviceType === serviceType 
            ? { ...rate, commissionPercentage: newRate.toString() }
            : rate
        )
      );
      
      setEditingCommission(null);
      toast({
        title: 'Éxito',
        description: 'Comisión actualizada correctamente',
      });
    } catch (error: any) {
      console.error('Error updating commission:', error);
      toast({
        title: 'Error',
        description: 'No se pudo actualizar la comisión',
        variant: 'destructive',
      });
    }
  };

  const processSettlement = async () => {
    if (!selectedSettlement) return;

    try {
      if (settlementProof) {
        await adminApi.uploadSettlementProof(settlementProof, selectedSettlement.id);
      }

      await adminApi.processSettlement(selectedSettlement.id);

      toast({
        title: 'Éxito',
        description: 'Liquidación procesada correctamente',
      });

      setShowSettlementModal(false);
      setSelectedSettlement(null);
      setSettlementProof(null);
      setSettlementNotes('');
      loadSettlements();
    } catch (error: any) {
      console.error('Error processing settlement:', error);
      toast({
        title: 'Error',
        description: 'No se pudo procesar la liquidación',
        variant: 'destructive',
      });
    }
  };

  const formatCurrency = (amount: string | number, currency = 'USD') => {
    const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount;
    return new Intl.NumberFormat('es-DO', {
      style: 'currency',
      currency: currency,
    }).format(numAmount);
  };

  const getServiceTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      hotel: 'Hotel',
      restaurant: 'Restaurante',
      tour_guide: 'Guía Turístico',
      taxi: 'Taxi',
      commerce: 'Comercio'
    };
    return labels[type] || type;
  };

  const getStatusBadge = (status: string) => {
    const variants: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
      settled: 'default',
      pending: 'secondary',
      failed: 'destructive',
      processing: 'outline'
    };
    
    const labels: Record<string, string> = {
      settled: 'Liquidado',
      pending: 'Pendiente',
      failed: 'Fallido',
      processing: 'Procesando'
    };

    return (
      <Badge variant={variants[status] || 'outline'}>
        {labels[status] || status}
      </Badge>
    );
  };

  const getPaymentMethodIcon = (type: string) => {
    switch (type) {
      case 'bank_transfer':
        return <Building className="h-4 w-4" />;
      case 'paypal':
        return <Mail className="h-4 w-4" />;
      default:
        return <CreditCard className="h-4 w-4" />;
    }
  };

  const renderDashboard = () => (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-black">Dashboard Financiero</h3>
      </div>

      {/* Overview Cards */}
      {overview && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium text-black">Ingresos Totales</CardTitle>
              <DollarSign className="h-4 w-4 text-gray-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-black">{formatCurrency(overview.totalRevenue)}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium text-black">Comisiones</CardTitle>
              <PieChart className="h-4 w-4 text-gray-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-black">{formatCurrency(overview.totalCommissions)}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium text-black">Ingresos Netos</CardTitle>
              <TrendingUp className="h-4 w-4 text-gray-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-black">{formatCurrency(overview.netRevenue)}</div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium text-black">Liquidaciones Pendientes</CardTitle>
              <Clock className="h-4 w-4 text-gray-600" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold text-black">{overview.pendingSettlements}</div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Revenue Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Ingresos y Comisiones</CardTitle>
            <CardDescription className="text-black">Comparación mensual de ingresos totales vs comisiones</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={revenueData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => formatCurrency(value as number)} />
                <Bar dataKey="revenue" fill="#F84525" name="Ingresos" />
                <Bar dataKey="commissions" fill="#FF6B35" name="Comisiones" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Service Type Distribution */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Distribución por Tipo de Servicio</CardTitle>
            <CardDescription className="text-black">Porcentaje de ingresos por categoría</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <RechartsPieChart>
                <RechartsPieChart data={serviceTypeData} cx="50%" cy="50%" outerRadius={80} dataKey="value">
                  {serviceTypeData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </RechartsPieChart>
                <Tooltip formatter={(value) => `${value}%`} />
              </RechartsPieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Transaction Trends */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Tendencia de Transacciones</CardTitle>
            <CardDescription className="text-black">Número de transacciones por día de la semana</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <LineChart data={transactionTrendsData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="day" />
                <YAxis />
                <Tooltip />
                <Line type="monotone" dataKey="transactions" stroke="#F84525" strokeWidth={2} />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Growth Area Chart */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Crecimiento Acumulado</CardTitle>
            <CardDescription className="text-black">Evolución de ingresos totales</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={revenueData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => formatCurrency(value as number)} />
                <Area type="monotone" dataKey="revenue" stroke="#F84525" fill="#F84525" fillOpacity={0.3} />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>
    </div>
  );

  const renderTransactions = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-black">Gestión de Transacciones</h3>
      
      <Card>
        <CardHeader>
          <CardTitle className="text-black">Transacciones Financieras</CardTitle>
          <CardDescription className="text-black">
            Historial completo de transacciones y pagos
          </CardDescription>
        </CardHeader>
        <CardContent>
          {/* Filters */}
          <div className="flex gap-4 mb-6">
            <div className="flex-1">
              <Label htmlFor="status-filter" className="text-black">Estado</Label>
              <Select 
                value={transactionFilters.status} 
                onValueChange={(value) => setTransactionFilters(prev => ({ ...prev, status: value, page: 1 }))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Todos los estados" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos</SelectItem>
                  <SelectItem value="pending">Pendiente</SelectItem>
                  <SelectItem value="settled">Liquidado</SelectItem>
                  <SelectItem value="failed">Fallido</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div className="flex-1">
              <Label htmlFor="service-filter" className="text-black">Tipo de Servicio</Label>
              <Select 
                value={transactionFilters.serviceType} 
                onValueChange={(value) => setTransactionFilters(prev => ({ ...prev, serviceType: value, page: 1 }))}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Todos los servicios" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos</SelectItem>
                  <SelectItem value="hotel">Hotel</SelectItem>
                  <SelectItem value="restaurant">Restaurante</SelectItem>
                  <SelectItem value="tour_guide">Guía Turístico</SelectItem>
                  <SelectItem value="taxi">Taxi</SelectItem>
                  <SelectItem value="commerce">Comercio</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-black">ID</TableHead>
                <TableHead className="text-black">Comercio</TableHead>
                <TableHead className="text-black">Tipo</TableHead>
                <TableHead className="text-black">Monto Bruto</TableHead>
                <TableHead className="text-black">Comisión</TableHead>
                <TableHead className="text-black">Monto Neto</TableHead>
                <TableHead className="text-black">Estado</TableHead>
                <TableHead className="text-black">Fecha</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {transactions.map((transaction) => (
                <TableRow key={transaction.id}>
                  <TableCell className="font-mono text-xs text-black">
                    {transaction.id.slice(0, 8)}...
                  </TableCell>
                  <TableCell>
                    <div>
                      <div className="font-medium text-black">
                        {transaction.merchant.firstName} {transaction.merchant.lastName}
                      </div>
                      <div className="text-sm text-gray-600">
                        {transaction.merchant.email}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {getServiceTypeLabel(transaction.serviceType)}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-black">{formatCurrency(transaction.grossAmount, transaction.currency)}</TableCell>
                  <TableCell>
                    <div>
                      <div className="text-black">{formatCurrency(transaction.commissionAmount, transaction.currency)}</div>
                      <div className="text-xs text-gray-600">
                        {parseFloat(transaction.commissionRate).toFixed(1)}%
                      </div>
                    </div>
                  </TableCell>
                  <TableCell className="text-black">{formatCurrency(transaction.netAmount, transaction.currency)}</TableCell>
                  <TableCell>{getStatusBadge(transaction.status)}</TableCell>
                  <TableCell className="text-black">
                    {new Date(transaction.createdAt).toLocaleDateString('es-DO')}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );

  const renderSettlements = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-black">Liquidaciones Pendientes</h3>
      
      <Card>
        <CardHeader>
          <CardTitle className="text-black">Gestión de Liquidaciones</CardTitle>
          <CardDescription className="text-black">
            Procesa los pagos pendientes a comercios, hoteles, restaurantes y guías
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-black">Comercio</TableHead>
                <TableHead className="text-black">Monto Total</TableHead>
                <TableHead className="text-black">Transacciones</TableHead>
                <TableHead className="text-black">Estado</TableHead>
                <TableHead className="text-black">Fecha</TableHead>
                <TableHead className="text-black">Acciones</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {settlements.map((settlement) => (
                <TableRow key={settlement.id}>
                  <TableCell>
                    <div>
                      <div className="font-medium text-black">
                        {settlement.merchant.firstName} {settlement.merchant.lastName}
                      </div>
                      <div className="text-sm text-gray-600">
                        {settlement.merchant.email}
                      </div>
                      <div className="text-sm text-gray-600">
                        <Phone className="h-3 w-3 inline mr-1" />
                        {settlement.merchant.phone}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="font-semibold text-lg text-black">
                      {formatCurrency(settlement.totalNet)}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {settlement.transactionCount} transacciones
                    </Badge>
                  </TableCell>
                  <TableCell>{getStatusBadge(settlement.status)}</TableCell>
                  <TableCell className="text-black">
                    {new Date(settlement.createdAt).toLocaleDateString('es-DO')}
                  </TableCell>
                  <TableCell>
                    <Button
                      size="sm"
                      onClick={() => {
                        setSelectedSettlement(settlement);
                        loadMerchantPaymentMethods(settlement.merchantId);
                        loadSettlementTransactions(settlement);
                        setShowSettlementModal(true);
                      }}
                      disabled={settlement.status !== 'pending'}
                    >
                      <PayIcon className="h-4 w-4 mr-2" />
                      Liquidar
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Settlement Modal */}
      <Dialog open={showSettlementModal} onOpenChange={setShowSettlementModal}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="text-black">Liquidar Pago</DialogTitle>
            <DialogDescription className="text-black">
              Procesa el pago para {selectedSettlement?.merchant.firstName} {selectedSettlement?.merchant.lastName}
            </DialogDescription>
          </DialogHeader>

          {selectedSettlement && (
            <div className="space-y-6">
              {/* Settlement Details */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm font-medium text-black">Monto a Liquidar</Label>
                  <p className="text-2xl font-bold text-green-600">
                    {formatCurrency(selectedSettlement.totalNet)}
                  </p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-black">Total de Transacciones</Label>
                  <p className="text-lg text-black">{selectedSettlement.transactionCount}</p>
                </div>
              </div>

              <Separator />

              {/* Transaction Details */}
              <div>
                <Label className="text-sm font-medium text-black mb-3 block">Detalle de Transacciones a Liquidar</Label>
                <div className="border rounded-lg overflow-hidden max-h-80 overflow-y-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="text-black text-xs">Fecha</TableHead>
                        <TableHead className="text-black text-xs">Servicio</TableHead>
                        <TableHead className="text-black text-xs">Monto Bruto</TableHead>
                        <TableHead className="text-black text-xs">Comisión</TableHead>
                        <TableHead className="text-black text-xs">Monto Comercio</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {settlementTransactions.length > 0 ? (
                        settlementTransactions.map((transaction) => (
                          <TableRow key={transaction.id}>
                            <TableCell className="text-black text-xs">
                              {new Date(transaction.createdAt).toLocaleDateString('es-DO', {
                                day: '2-digit',
                                month: '2-digit',
                                year: '2-digit'
                              })}
                            </TableCell>
                            <TableCell>
                              <Badge variant="outline" className="text-xs">
                                {getServiceTypeLabel(transaction.serviceType)}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-black text-xs font-medium">
                              {formatCurrency(transaction.grossAmount, transaction.currency)}
                            </TableCell>
                            <TableCell className="text-red-600 text-xs font-medium">
                              -{formatCurrency(transaction.commissionAmount, transaction.currency)}
                            </TableCell>
                            <TableCell className="text-green-600 text-xs font-bold">
                              {formatCurrency(transaction.netAmount, transaction.currency)}
                            </TableCell>
                          </TableRow>
                        ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={5} className="text-center text-gray-500 text-sm py-8">
                            No hay transacciones disponibles para mostrar
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </div>
                
                {/* Summary Row */}
                <div className="mt-3 p-3 bg-gray-50 rounded-lg">
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <span className="text-gray-600">Total Bruto:</span>
                      <div className="font-bold text-black">{formatCurrency(selectedSettlement.totalGross)}</div>
                    </div>
                    <div>
                      <span className="text-gray-600">Comisión Total:</span>
                      <div className="font-bold text-red-600">-{formatCurrency(selectedSettlement.totalCommission)}</div>
                    </div>
                    <div>
                      <span className="text-gray-600">A Liquidar:</span>
                      <div className="font-bold text-green-600">{formatCurrency(selectedSettlement.totalNet)}</div>
                    </div>
                  </div>
                </div>
              </div>

              <Separator />

              {/* Merchant Contact Info */}
              <div>
                <Label className="text-sm font-medium text-black">Información de Contacto</Label>
                <div className="mt-2 space-y-2">
                  <div className="flex items-center gap-2">
                    <Mail className="h-4 w-4 text-gray-600" />
                    <span className="text-black">{selectedSettlement.merchant.email}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Phone className="h-4 w-4 text-gray-600" />
                    <span className="text-black">{selectedSettlement.merchant.phone}</span>
                  </div>
                </div>
              </div>

              <Separator />

              {/* Payment Methods */}
              <div>
                <Label className="text-sm font-medium text-black">Medios de Pago Registrados</Label>
                <div className="mt-2 space-y-3">
                  {paymentMethods.map((method) => (
                    <div key={method.id} className="flex items-center gap-3 p-3 border rounded-lg">
                      {getPaymentMethodIcon(method.type)}
                      <div className="flex-1">
                        <div className="font-medium text-black">{method.details}</div>
                        {method.accountHolder && (
                          <div className="text-sm text-gray-600">
                            Titular: {method.accountHolder}
                          </div>
                        )}
                        {method.accountNumber && (
                          <div className="text-sm text-gray-600">
                            Cuenta: {method.accountNumber}
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              <Separator />

              {/* Upload Proof */}
              <div>
                <Label className="text-sm font-medium text-black">Comprobante de Pago</Label>
                <div className="mt-2">
                  <Input
                    type="file"
                    accept="image/*,.pdf"
                    onChange={(e) => setSettlementProof(e.target.files?.[0] || null)}
                    className="mb-2"
                  />
                  <p className="text-xs text-gray-600">
                    Sube una imagen o PDF del comprobante de transferencia
                  </p>
                </div>
              </div>

              {/* Notes */}
              <div>
                <Label className="text-sm font-medium text-black">Notas (Opcional)</Label>
                <Textarea
                  value={settlementNotes}
                  onChange={(e) => setSettlementNotes(e.target.value)}
                  placeholder="Agrega notas sobre esta liquidación..."
                  className="mt-2"
                />
              </div>

              {/* Actions */}
              <div className="flex gap-3 justify-end">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowSettlementModal(false);
                    setSelectedSettlement(null);
                    setSettlementProof(null);
                    setSettlementNotes('');
                  }}
                >
                  Cancelar
                </Button>
                <Button onClick={processSettlement} className="bg-green-600 hover:bg-green-700">
                  <Check className="h-4 w-4 mr-2" />
                  Confirmar Liquidación
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );

  const renderCommissions = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-black">Configuración de Comisiones</h3>
      
      <Card>
        <CardHeader>
          <CardTitle className="text-black">Gestión de Comisiones</CardTitle>
          <CardDescription className="text-black">
            Gestiona los porcentajes de comisión por tipo de servicio
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-black">Tipo de Servicio</TableHead>
                <TableHead className="text-black">Porcentaje de Comisión</TableHead>
                <TableHead className="text-black">Estado</TableHead>
                <TableHead className="text-black">Última Actualización</TableHead>
                {isSuperAdmin && <TableHead className="text-black">Acciones</TableHead>}
              </TableRow>
            </TableHeader>
            <TableBody>
              {commissionRates.map((rate) => (
                <TableRow key={rate.id}>
                  <TableCell>
                    <Badge variant="outline">
                      {getServiceTypeLabel(rate.serviceType)}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {editingCommission === rate.serviceType ? (
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          max="100"
                          value={editValue}
                          onChange={(e) => setEditValue(e.target.value)}
                          className="w-20"
                        />
                        <span className="text-black">%</span>
                      </div>
                    ) : (
                      <span className="font-medium text-black">
                        {parseFloat(rate.commissionPercentage).toFixed(1)}%
                      </span>
                    )}
                  </TableCell>
                  <TableCell>
                    <Badge variant={rate.active ? 'default' : 'secondary'}>
                      {rate.active ? 'Activo' : 'Inactivo'}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-black">
                    {new Date(rate.updatedAt).toLocaleDateString('es-DO')}
                  </TableCell>
                  {isSuperAdmin && (
                    <TableCell>
                      {editingCommission === rate.serviceType ? (
                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            onClick={() => updateCommissionRate(rate.serviceType, parseFloat(editValue))}
                          >
                            <Save className="h-4 w-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => {
                              setEditingCommission(null);
                              setEditValue('');
                            }}
                          >
                            <X className="h-4 w-4" />
                          </Button>
                        </div>
                      ) : (
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => {
                            setEditingCommission(rate.serviceType);
                            setEditValue(rate.commissionPercentage);
                          }}
                        >
                          <Edit2 className="h-4 w-4" />
                        </Button>
                      )}
                    </TableCell>
                  )}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );

  const renderReports = () => (
    <div className="space-y-6">
      <h3 className="text-lg font-semibold text-black">Reportes Financieros</h3>
      
      {/* Advanced Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="text-black">Filtros Avanzados</CardTitle>
          <CardDescription className="text-black">Configura filtros detallados para generar reportes específicos</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
            <div>
              <Label className="text-black">Rango de Fechas</Label>
              <div className="space-y-2">
                <Input
                  type="date"
                  placeholder="Fecha Inicio"
                  value={reportDateRange.startDate}
                  onChange={(e) => setReportDateRange(prev => ({ ...prev, startDate: e.target.value }))}
                />
                <Input
                  type="date"
                  placeholder="Fecha Final"
                  value={reportDateRange.endDate}
                  onChange={(e) => setReportDateRange(prev => ({ ...prev, endDate: e.target.value }))}
                />
              </div>
            </div>
            
            <div>
              <Label className="text-black">Comercio/Negocio</Label>
              <Select value={reportFilters.merchant} onValueChange={(value) => setReportFilters(prev => ({ ...prev, merchant: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="Seleccionar comercio" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos los comercios</SelectItem>
                  <SelectItem value="hotels">Hoteles</SelectItem>
                  <SelectItem value="restaurants">Restaurantes</SelectItem>
                  <SelectItem value="guides">Guías turísticos</SelectItem>
                  <SelectItem value="transport">Transporte</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label className="text-black">Tipo de Servicio</Label>
              <Select value={reportFilters.serviceType} onValueChange={(value) => setReportFilters(prev => ({ ...prev, serviceType: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="Tipo de servicio" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos los servicios</SelectItem>
                  <SelectItem value="hotel">Hotel</SelectItem>
                  <SelectItem value="restaurant">Restaurante</SelectItem>
                  <SelectItem value="tour_guide">Guía turístico</SelectItem>
                  <SelectItem value="taxi">Taxi</SelectItem>
                  <SelectItem value="commerce">Comercio</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label className="text-black">Estado</Label>
              <Select value={reportFilters.status} onValueChange={(value) => setReportFilters(prev => ({ ...prev, status: value }))}>
                <SelectTrigger>
                  <SelectValue placeholder="Estado" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Todos los estados</SelectItem>
                  <SelectItem value="pending">Pendiente</SelectItem>
                  <SelectItem value="processing">Procesando</SelectItem>
                  <SelectItem value="completed">Completado</SelectItem>
                  <SelectItem value="settled">Liquidado</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="flex gap-4 items-center">
            <Button variant="outline">
              <Filter className="h-4 w-4 mr-2" />
              Aplicar Filtros
            </Button>
            <Button>
              <Download className="h-4 w-4 mr-2" />
              Exportar PDF
            </Button>
            <Button variant="ghost" onClick={() => {
              setReportFilters({ merchant: 'all', serviceType: 'all', status: 'all', transactionType: 'all' });
              setReportDateRange({ startDate: '', endDate: '' });
            }}>
              Limpiar Filtros
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Financial Summary Charts */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Monthly Revenue Comparison */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Comparación de Ingresos Mensuales</CardTitle>
            <CardDescription className="text-black">Análisis detallado de ingresos vs gastos</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={350}>
              <BarChart data={revenueData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => formatCurrency(value as number)} />
                <Bar dataKey="revenue" fill="#F84525" name="Ingresos Brutos" />
                <Bar dataKey="commissions" fill="#FF6B35" name="Comisiones Karibeo" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Service Performance */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Rendimiento por Servicio</CardTitle>
            <CardDescription className="text-black">Distribución de ingresos por categoría</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={350}>
              <RechartsPieChart>
                <RechartsPieChart data={serviceTypeData} cx="50%" cy="50%" outerRadius={80} dataKey="value">
                  {serviceTypeData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </RechartsPieChart>
                <Tooltip formatter={(value) => `${value}%`} />
              </RechartsPieChart>
            </ResponsiveContainer>
            <div className="mt-4 grid grid-cols-2 gap-2">
              {serviceTypeData.map((item, index) => (
                <div key={item.name} className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full" style={{ backgroundColor: COLORS[index] }}></div>
                  <span className="text-sm text-black">{item.name}: {item.value}%</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* Commission Trends */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Tendencia de Comisiones</CardTitle>
            <CardDescription className="text-black">Evolución de comisiones generadas</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={350}>
              <LineChart data={revenueData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="month" />
                <YAxis />
                <Tooltip formatter={(value) => formatCurrency(value as number)} />
                <Line 
                  type="monotone" 
                  dataKey="commissions" 
                  stroke="#F84525" 
                  strokeWidth={3}
                  dot={{ fill: '#F84525', strokeWidth: 2, r: 4 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Transaction Volume */}
        <Card>
          <CardHeader>
            <CardTitle className="text-black">Volumen de Transacciones</CardTitle>
            <CardDescription className="text-black">Número de transacciones procesadas</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={350}>
              <AreaChart data={transactionTrendsData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="day" />
                <YAxis />
                <Tooltip />
                <Area 
                  type="monotone" 
                  dataKey="transactions" 
                  stroke="#F84525" 
                  fill="#F84525" 
                  fillOpacity={0.6}
                />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* Summary Table */}
      <Card>
        <CardHeader>
          <CardTitle className="text-black">Resumen Ejecutivo</CardTitle>
          <CardDescription className="text-black">Métricas clave del período seleccionado</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="text-black">Métrica</TableHead>
                <TableHead className="text-black">Valor</TableHead>
                <TableHead className="text-black">Cambio vs Período Anterior</TableHead>
                <TableHead className="text-black">Tendencia</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              <TableRow>
                <TableCell className="text-black font-medium">Ingresos Totales</TableCell>
                <TableCell className="text-black font-bold">{formatCurrency(2250)}</TableCell>
                <TableCell className="text-green-600">+15.3%</TableCell>
                <TableCell><TrendingUp className="h-4 w-4 text-green-600" /></TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="text-black font-medium">Comisiones Generadas</TableCell>
                <TableCell className="text-black font-bold">{formatCurrency(200)}</TableCell>
                <TableCell className="text-green-600">+12.1%</TableCell>
                <TableCell><TrendingUp className="h-4 w-4 text-green-600" /></TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="text-black font-medium">Transacciones Procesadas</TableCell>
                <TableCell className="text-black font-bold">9</TableCell>
                <TableCell className="text-green-600">+22.2%</TableCell>
                <TableCell><TrendingUp className="h-4 w-4 text-green-600" /></TableCell>
              </TableRow>
              <TableRow>
                <TableCell className="text-black font-medium">Ticket Promedio</TableCell>
                <TableCell className="text-black font-bold">{formatCurrency(250)}</TableCell>
                <TableCell className="text-red-600">-5.8%</TableCell>
                <TableCell><TrendingUp className="h-4 w-4 text-red-600 rotate-180" /></TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );

  const renderContent = () => {
    switch (activeSection) {
      case 'dashboard':
        return renderDashboard();
      case 'transactions':
        return renderTransactions();
      case 'settlements':
        return renderSettlements();
      case 'commissions':
        return renderCommissions();
      case 'reports':
        return renderReports();
      default:
        return renderDashboard();
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold text-black">Gestión Financiera</h2>
        <div className="flex items-center gap-4">
          <div className="flex bg-white rounded-lg p-1 border">
            {menuItems.map((item) => (
              <Button
                key={item.id}
                variant={activeSection === item.id ? "default" : "ghost"}
                size="sm"
                onClick={() => setActiveSection(item.id)}
                className={`flex items-center gap-2 ${
                  activeSection === item.id 
                    ? 'bg-primary text-white' 
                    : 'text-black hover:bg-gray-100'
                }`}
              >
                <item.icon className="h-4 w-4" />
                <span className="hidden sm:inline">{item.label}</span>
              </Button>
            ))}
          </div>
          
          {activeSection === 'dashboard' && (
            <Select value={period} onValueChange={setPeriod}>
              <SelectTrigger className="w-40">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="day">Hoy</SelectItem>
                <SelectItem value="week">Esta Semana</SelectItem>
                <SelectItem value="month">Este Mes</SelectItem>
                <SelectItem value="year">Este Año</SelectItem>
              </SelectContent>
            </Select>
          )}
        </div>
      </div>

      <div className="text-black">
        {renderContent()}
      </div>
    </div>
  );
};

export default FinancialTab;