import React, { useState, useEffect } from 'react';
import { 
  BarChart3, 
  FileText,
  Calendar, 
  Users, 
  Hotel, 
  TrendingUp,
  Download,
  Filter,
  PieChart,
  Search,
  Eye,
  Activity,
  AlertCircle,
  CheckCircle,
  XCircle,
  Info,
  Sparkles,
  ClipboardList,
  X,
  Star,
  RefreshCw,
  Plus,
  DollarSign,
  CreditCard,
  Building2,
  Target,
  Award
} from 'lucide-react';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import ExportButton from '../../shared/components/ExportButton';
import Pagination from '../../shared/components/Pagination';
import CurrencyIcon from '../../shared/components/CurrencyIcon';
import { useAsync } from '../../shared/hooks/useAsync';
import reportService, { ReportData } from '../../features/analytics/services/reportService';
import reviewService, { Review } from '../../features/reviews/services/reviewService';
import { auditService, AuditLog, AuditLogFilters } from '../../features/analytics/services/auditService';
import { formatDate } from '../../shared/utils/format';
import { useFormatCurrency } from '../../features/payments/hooks/useFormatCurrency';
import { logger } from '../../shared/utils/logger';
import analyticsService, {
  ComprehensiveAnalyticsData,
  RevPARData,
  ADRData,
  OccupancyRateData,
  RevenueForecastData,
  MarketPenetrationData,
  StaffPerformanceData,
  ServiceUsageData,
  OperationalEfficiencyData,
  GuestLTVData,
  RepeatGuestRateData,
  GuestSatisfactionTrendsData,
  ProfitLossData,
  PaymentMethodAnalyticsData,
  RefundAnalysisData,
} from '../../features/analytics/services/analyticsService';
import { SimpleBarChart, SimpleLineChart, SimplePieChart, KPICard } from '../../features/analytics/components/SimpleChart';
import { exportData } from '../../shared/utils/exportUtils';
import CustomReportBuilder from '../../features/analytics/components/CustomReportBuilder';

type AnalyticsTab = 'overview' | 'reports' | 'revenue' | 'operational' | 'guest' | 'financial' | 'audit-logs' | 'reviews';

const AnalyticsDashboardPage: React.FC = () => {
  const { formatCurrency } = useFormatCurrency();
  const [activeTab, setActiveTab] = useState<AnalyticsTab>('overview');
  const [showReportBuilder, setShowReportBuilder] = useState(false);
  const [analyticsDateRange, setAnalyticsDateRange] = useState({
    from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
    to: new Date().toISOString().split('T')[0],
  });

  
  const [dateRange, setDateRange] = useState({
    from: '',
    to: '',
  });
  const [reportType, setReportType] = useState<'daily' | 'weekly' | 'monthly' | 'yearly' | ''>('');

  
  const [logs, setLogs] = useState<AuditLog[]>([]);
  const [auditLoading, setAuditLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [showDetails, setShowDetails] = useState(false);
  const itemsPerPage = 20;

  const [auditFilters, setAuditFilters] = useState<AuditLogFilters>({
    page: 1,
    limit: itemsPerPage,
  });

  
  const [reviews, setReviews] = useState<Review[]>([]);
  const [reviewsLoading, setReviewsLoading] = useState(true);
  const [reviewsFilters, setReviewsFilters] = useState({
    status: '',
  });
  const [reviewsCurrentPage, setReviewsCurrentPage] = useState(1);
  const [reviewsTotalPages, setReviewsTotalPages] = useState(1);
  const [reviewsTotalItems, setReviewsTotalItems] = useState(0);
  const reviewsPerPage = 5;

  // Advanced Analytics Data
  const { data: comprehensiveData, loading: comprehensiveLoading, execute: fetchComprehensive } = useAsync<ComprehensiveAnalyticsData>(
    () => analyticsService.getComprehensiveAnalytics({
      from: analyticsDateRange.from,
      to: analyticsDateRange.to,
      include_revenue: true,
      include_operational: true,
      include_guest: true,
      include_financial: true,
    }).then(r => r.data),
    { immediate: true }
  );

  const { data: revparData, loading: revparLoading, execute: fetchRevPAR } = useAsync<RevPARData>(
    () => analyticsService.getRevPAR({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: adrData, loading: adrLoading, execute: fetchADR } = useAsync<ADRData>(
    () => analyticsService.getADR({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: occupancyData, loading: occupancyLoading, execute: fetchOccupancy } = useAsync<OccupancyRateData>(
    () => analyticsService.getOccupancyRate({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: forecastData, loading: forecastLoading, execute: fetchForecast } = useAsync<RevenueForecastData>(
    () => analyticsService.getRevenueForecast(30).then(r => r.data),
    { immediate: false }
  );

  const { data: marketPenetrationData, loading: marketLoading, execute: fetchMarketPenetration } = useAsync<MarketPenetrationData>(
    () => analyticsService.getMarketPenetration({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: staffPerformanceData, loading: staffLoading, execute: fetchStaffPerformance } = useAsync<StaffPerformanceData>(
    () => analyticsService.getStaffPerformance({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: serviceUsageData, loading: serviceLoading, execute: fetchServiceUsage } = useAsync<ServiceUsageData>(
    () => analyticsService.getServiceUsageAnalytics({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: efficiencyData, loading: efficiencyLoading, execute: fetchEfficiency } = useAsync<OperationalEfficiencyData>(
    () => analyticsService.getOperationalEfficiency({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: ltvData, loading: ltvLoading, execute: fetchLTV } = useAsync<GuestLTVData>(
    () => analyticsService.getGuestLifetimeValue({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: repeatRateData, loading: repeatLoading, execute: fetchRepeatRate } = useAsync<RepeatGuestRateData>(
    () => analyticsService.getRepeatGuestRate({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: satisfactionData, loading: satisfactionLoading, execute: fetchSatisfaction } = useAsync<GuestSatisfactionTrendsData>(
    () => analyticsService.getGuestSatisfactionTrends({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: profitLossData, loading: profitLossLoading, execute: fetchProfitLoss } = useAsync<ProfitLossData>(
    () => analyticsService.getProfitLoss({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: paymentMethodData, loading: paymentMethodLoading, execute: fetchPaymentMethods } = useAsync<PaymentMethodAnalyticsData>(
    () => analyticsService.getPaymentMethodAnalytics({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const { data: refundData, loading: refundLoading, execute: fetchRefunds } = useAsync<RefundAnalysisData>(
    () => analyticsService.getRefundAnalysis({ from: analyticsDateRange.from, to: analyticsDateRange.to }).then(r => r.data),
    { immediate: false }
  );

  const fetchReports = async (): Promise<ReportData> => {
    const params: Record<string, unknown> = {};
    if (dateRange.from) params.from = dateRange.from;
    if (dateRange.to) params.to = dateRange.to;
    if (reportType) params.type = reportType;

    const response = await reportService.getReports(params);
    return response.data;
  };

  const { 
    data: reportData, 
    loading: reportsLoading, 
    error: reportsError, 
    execute: refetchReports 
  } = useAsync<ReportData>(fetchReports, {
    immediate: true,
    onError: (error: unknown) => {
      const errorMessage = error instanceof Error ? error.message : 'Unable to load reports';
      toast.error(errorMessage);
    }
  });

  useEffect(() => {
    if (activeTab === 'audit-logs') {
      fetchLogs();
    } else if (activeTab === 'reviews') {
      fetchReviews();
    } else if (activeTab === 'overview') {
      fetchComprehensive();
    } else if (activeTab === 'revenue') {
      Promise.all([fetchRevPAR(), fetchADR(), fetchOccupancy(), fetchForecast(), fetchMarketPenetration()]);
    } else if (activeTab === 'operational') {
      Promise.all([fetchStaffPerformance(), fetchServiceUsage(), fetchEfficiency()]);
    } else if (activeTab === 'guest') {
      Promise.all([fetchLTV(), fetchRepeatRate(), fetchSatisfaction()]);
    } else if (activeTab === 'financial') {
      Promise.all([fetchProfitLoss(), fetchPaymentMethods(), fetchRefunds()]);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab, auditFilters, currentPage, reviewsFilters, reviewsCurrentPage, analyticsDateRange]);

  useEffect(() => {
    setAuditFilters(prev => ({ ...prev, page: currentPage }));
  }, [currentPage]);

  useEffect(() => {
    if (activeTab === 'reviews') {
      setReviewsCurrentPage(1);
    }
  }, [reviewsFilters, activeTab]);

  const fetchLogs = async () => {
    try {
      setAuditLoading(true);
      const response = await auditService.getAuditLogs({
        ...auditFilters,
        page: currentPage,
        limit: itemsPerPage,
      });
      setLogs(response.data.logs);
      if (response.data.pagination) {
        setTotalPages(response.data.pagination.totalPages);
        setTotalItems(response.data.pagination.total);
      }
    } catch (error: unknown) {
      logger.error('Error fetching audit logs', error);
      toast.error(getUserFriendlyError(error) || 'Unable to load audit logs');
    } finally {
      setAuditLoading(false);
    }
  };

  const handleExport = async (format: 'csv' | 'xlsx' | 'pdf' | 'json' = 'csv') => {
    try {
      // Handle analytics tabs export
      if (activeTab === 'overview' || activeTab === 'revenue' || activeTab === 'operational' || activeTab === 'guest' || activeTab === 'financial') {
        let exportDataArray: Array<Record<string, unknown>> = [];
        let filename = 'analytics';
        let title = 'Analytics Report';

        if (activeTab === 'overview' && comprehensiveData) {
          const revenue = comprehensiveData.revenue;
          if (revenue) {
            exportDataArray = [
              { Metric: 'RevPAR', Value: revenue.revpar.revpar },
              { Metric: 'ADR', Value: revenue.adr.adr },
              { Metric: 'Occupancy Rate', Value: `${revenue.occupancy_rate.occupancy_rate}%` },
            ];
          }
          filename = 'comprehensive-analytics';
          title = 'Comprehensive Analytics Report';
        } else if (activeTab === 'revenue' && comprehensiveData?.revenue) {
          const revenue = comprehensiveData.revenue;
          exportDataArray = [
            { Metric: 'RevPAR', Value: revenue.revpar.revpar },
            { Metric: 'ADR', Value: revenue.adr.adr },
            { Metric: 'Occupancy Rate', Value: `${revenue.occupancy_rate.occupancy_rate}%` },
          ];
          filename = 'revenue-analytics';
          title = 'Revenue Analytics Report';
        } else if (activeTab === 'operational' && comprehensiveData?.operational) {
          const operational = comprehensiveData.operational;
          exportDataArray = operational.staff_performance.staff_performance.map(staff => ({
            'Staff Name': staff.staff_name,
            'Email': staff.email,
            'Check-ins Handled': staff.check_ins_handled,
            'Performance Score': staff.performance_score,
          }));
          filename = 'operational-analytics';
          title = 'Operational Analytics Report';
        } else if (activeTab === 'guest' && comprehensiveData?.guest) {
          const guest = comprehensiveData.guest;
          exportDataArray = guest.lifetime_value.guests.slice(0, 50).map(g => ({
            'Guest Name': g.name,
            'Email': g.email,
            'Total Bookings': g.total_bookings,
            'Lifetime Value': g.lifetime_value,
            'Average Booking Value': g.average_booking_value,
          }));
          filename = 'guest-analytics';
          title = 'Guest Analytics Report';
        } else if (activeTab === 'financial' && comprehensiveData?.financial) {
          const financial = comprehensiveData.financial;
          exportDataArray = financial.payment_methods.payment_methods.map(pm => ({
            'Payment Method': pm.payment_method,
            'Transaction Count': pm.transaction_count,
            'Total Amount': pm.total_amount,
            'Average Amount': pm.average_amount,
            'Percentage': `${pm.percentage}%`,
          }));
          filename = 'financial-analytics';
          title = 'Financial Analytics Report';
        }

        if (exportDataArray.length > 0) {
          exportData({
            filename,
            title,
            data: exportDataArray,
            format,
          });
          toast.success(`Exported ${format.toUpperCase()} successfully`);
          return;
        }
      }

      // Handle reports tab export (existing functionality)
      const params: Record<string, unknown> = {};
      if (dateRange.from) params.from = dateRange.from;
      if (dateRange.to) params.to = dateRange.to;
      if (reportType) params.type = reportType;

      const blob = await reportService.exportReport(params);
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `report-${new Date().toISOString().split('T')[0]}.csv`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      toast.success('Report exported successfully');
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Failed to export report');
    }
  };

  const handleFilter = () => {
    refetchReports();
  };

  const handleAuditFilterChange = (key: keyof AuditLogFilters, value: string | number | undefined) => {
    setAuditFilters(prev => ({ ...prev, [key]: value }));
    setCurrentPage(1);
  };

  const handleSearch = (searchTerm: string) => {
    handleAuditFilterChange('search', searchTerm || undefined);
  };

  const handleViewDetails = (log: AuditLog) => {
    setSelectedLog(log);
    setShowDetails(true);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'success':
        return <CheckCircle className="w-5 h-5 text-emerald-500" />;
      case 'failed':
        return <XCircle className="w-5 h-5 text-red-500" />;
      case 'error':
        return <AlertCircle className="w-5 h-5 text-amber-500" />;
      default:
        return <Info className="w-5 h-5 text-gray-500" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const baseClasses = "px-3 py-1 rounded-full text-xs font-semibold";
    switch (status) {
      case 'success':
        return `${baseClasses} bg-emerald-100 text-emerald-800 border border-emerald-200`;
      case 'failed':
        return `${baseClasses} bg-red-100 text-red-800 border border-red-200`;
      case 'error':
        return `${baseClasses} bg-amber-100 text-amber-800 border border-amber-200`;
      default:
        return `${baseClasses} bg-gray-100 text-gray-800 border border-gray-200`;
    }
  };

  
  const fetchReviews = async () => {
    try {
      setReviewsLoading(true);
      const response = await reviewService.getReviews({
        ...reviewsFilters,
        page: reviewsCurrentPage,
        limit: reviewsPerPage,
      });
      setReviews(response.data.reviews);
      if (response.data.pagination) {
        setReviewsTotalPages(response.data.pagination.totalPages);
        setReviewsTotalItems(response.data.pagination.total);
      }
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load reviews list');
    } finally {
      setReviewsLoading(false);
    }
  };

  const handleApproveReview = async (id: number) => {
    try {
      await reviewService.approveReview(id);
      toast.success('Review approved successfully');
      fetchReviews();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to approve review');
    }
  };

  const handleRejectReview = async (id: number) => {
    if (!window.confirm('Are you sure you want to reject this review?')) return;
    
    try {
      await reviewService.rejectReview(id);
      toast.success('Review rejected successfully');
      fetchReviews();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to reject review');
    }
  };

  const getReviewStatusBadge = (status: string) => {
    const badges: Record<string, { bg: string; text: string; label: string; border: string }> = {
      pending: { bg: 'bg-gradient-to-r from-amber-50 to-yellow-50', text: 'text-amber-800', label: 'Pending', border: 'border-amber-200' },
      approved: { bg: 'bg-gradient-to-r from-emerald-50 to-green-50', text: 'text-emerald-800', label: 'Approved', border: 'border-emerald-200' },
      rejected: { bg: 'bg-gradient-to-r from-rose-50 to-red-50', text: 'text-rose-800', label: 'Rejected', border: 'border-rose-200' },
    };
    const badge = badges[status] || badges.pending;
    return (
      <span className={`px-3 py-1.5 rounded-full text-xs font-semibold border shadow-sm ${badge.bg} ${badge.text} ${badge.border}`}>
        {badge.label}
      </span>
    );
  };

  const renderStars = (rating: number) => {
    return (
      <div className="flex items-center gap-0.5">
        {[1, 2, 3, 4, 5].map((star) => (
          <Star 
            key={star} 
            className={`w-4 h-4 ${star <= rating ? 'text-amber-400 fill-amber-400' : 'text-gray-300'}`}
          />
        ))}
      </div>
    );
  };

  const tabs = [
    { id: 'overview' as AnalyticsTab, label: 'Overview', icon: BarChart3 },
    { id: 'revenue' as AnalyticsTab, label: 'Revenue', icon: DollarSign },
    { id: 'operational' as AnalyticsTab, label: 'Operational', icon: Activity },
    { id: 'guest' as AnalyticsTab, label: 'Guest', icon: Users },
    { id: 'financial' as AnalyticsTab, label: 'Financial', icon: CreditCard },
    { id: 'reports' as AnalyticsTab, label: 'Reports', icon: FileText },
    { id: 'audit-logs' as AnalyticsTab, label: 'Audit Logs', icon: ClipboardList },
    { id: 'reviews' as AnalyticsTab, label: 'Reviews', icon: Star },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-10 animate-fade-in">
        {}
        <div className="relative">
          <div className="absolute inset-0 bg-gradient-to-r from-blue-400/5 via-transparent to-indigo-600/5 rounded-3xl blur-3xl"></div>
          <div className="relative bg-white/80 backdrop-blur-xl rounded-3xl shadow-2xl border border-blue-200/30 p-8 md:p-10">
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-8">
              <div className="flex items-start gap-5">
                <div className="relative">
                  <div className="absolute inset-0 bg-gradient-to-br from-blue-400 to-indigo-600 rounded-2xl blur-lg opacity-50"></div>
                  <div className="relative p-4 rounded-2xl bg-gradient-to-br from-blue-500 via-blue-500 to-indigo-600 shadow-xl border border-blue-400/50">
                    <BarChart3 className="w-8 h-8 text-white" />
                    <div className="absolute -top-1 -right-1 w-4 h-4 bg-gradient-to-br from-cyan-300 to-blue-500 rounded-full shadow-lg animate-pulse"></div>
                  </div>
                </div>
                <div className="space-y-3 flex-1">
                  <div className="flex items-center gap-3">
                    <h1 className="text-4xl md:text-5xl font-extrabold bg-gradient-to-r from-slate-900 via-blue-700 to-slate-900 bg-clip-text text-transparent">
                      Analytics Dashboard
                    </h1>
                    <Sparkles className="w-6 h-6 text-blue-500 animate-pulse" />
                  </div>
                  <p className="text-gray-600 text-base md:text-lg max-w-2xl leading-relaxed">
                    Comprehensive insights, reports, and system activity tracking
                  </p>
                </div>
              </div>
              {(activeTab === 'overview' || activeTab === 'revenue' || activeTab === 'operational' || activeTab === 'guest' || activeTab === 'financial') && (
                <div className="mt-6 flex items-center gap-3 flex-wrap">
                  <div className="flex items-center gap-2">
                    <Calendar className="w-5 h-5 text-gray-500" />
                    <input
                      type="date"
                      value={analyticsDateRange.from}
                      onChange={(e) => setAnalyticsDateRange({ ...analyticsDateRange, from: e.target.value })}
                      className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                    />
                    <span className="text-gray-500">to</span>
                    <input
                      type="date"
                      value={analyticsDateRange.to}
                      onChange={(e) => setAnalyticsDateRange({ ...analyticsDateRange, to: e.target.value })}
                      className="px-3 py-2 border border-gray-300 rounded-lg text-sm"
                    />
                  </div>
                  <button
                    onClick={() => {
                      if (activeTab === 'overview') fetchComprehensive();
                      else if (activeTab === 'revenue') Promise.all([fetchRevPAR(), fetchADR(), fetchOccupancy(), fetchForecast(), fetchMarketPenetration()]);
                      else if (activeTab === 'operational') Promise.all([fetchStaffPerformance(), fetchServiceUsage(), fetchEfficiency()]);
                      else if (activeTab === 'guest') Promise.all([fetchLTV(), fetchRepeatRate(), fetchSatisfaction()]);
                      else if (activeTab === 'financial') Promise.all([fetchProfitLoss(), fetchPaymentMethods(), fetchRefunds()]);
                    }}
                    className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2"
                  >
                    <RefreshCw className="w-4 h-4" />
                    Refresh
                  </button>
                  <button
                    onClick={() => setShowReportBuilder(true)}
                    className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-2"
                  >
                    <Plus className="w-4 h-4" />
                    Custom Report
                  </button>
                  <button
                    onClick={() => handleExport('csv')}
                    className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700 transition-colors flex items-center gap-2"
                  >
                    <Download className="w-4 h-4" />
                    Export
                  </button>
                </div>
              )}
            </div>

            {}
            <div className="mt-10 pt-8 border-t border-gradient-to-r from-transparent via-blue-200/30 to-transparent">
              <div className="flex flex-wrap gap-3">
                {tabs.map((tab) => {
                  const Icon = tab.icon;
                  const isActive = activeTab === tab.id;
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id)}
                      className={`
                        group relative flex items-center gap-3 px-6 py-3.5 rounded-xl font-semibold text-sm
                        transition-all duration-300 overflow-hidden
                        ${
                          isActive
                            ? 'bg-gradient-to-r from-blue-500 via-blue-500 to-indigo-600 text-white shadow-xl shadow-blue-500/40 scale-105'
                            : 'bg-white/80 text-gray-700 border border-gray-200/60 hover:border-blue-300/60 hover:bg-gradient-to-r hover:from-blue-50/50 hover:to-indigo-50/30 hover:shadow-lg hover:scale-102'
                        }
                      `}
                    >
                      {isActive && (
                        <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer"></div>
                      )}
                      <Icon className={`w-5 h-5 transition-transform duration-300 ${isActive ? 'text-white' : 'text-gray-600 group-hover:text-blue-600 group-hover:scale-110'}`} />
                      <span className="relative z-10">{tab.label}</span>
                      {isActive && (
                        <div className="absolute bottom-0 left-0 right-0 h-1 bg-gradient-to-r from-cyan-300 via-blue-400 to-indigo-400"></div>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {}
        {activeTab === 'overview' && (
          <div className="space-y-6">
            {comprehensiveLoading ? (
              <Loading fullScreen text="Loading analytics..." />
            ) : comprehensiveData ? (
              <>
                {/* Key Metrics */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {comprehensiveData.revenue && (
                    <>
                      <KPICard
                        title="RevPAR"
                        value={formatCurrency(comprehensiveData.revenue.revpar.revpar)}
                        icon={<TrendingUp className="w-6 h-6" />}
                        color="blue"
                      />
                      <KPICard
                        title="ADR"
                        value={formatCurrency(comprehensiveData.revenue.adr.adr)}
                        icon={<DollarSign className="w-6 h-6" />}
                        color="green"
                      />
                      <KPICard
                        title="Occupancy Rate"
                        value={`${comprehensiveData.revenue.occupancy_rate.occupancy_rate.toFixed(1)}%`}
                        icon={<Building2 className="w-6 h-6" />}
                        color="orange"
                      />
                      <KPICard
                        title="Net Revenue"
                        value={comprehensiveData.financial ? formatCurrency(comprehensiveData.financial.profit_loss.net_revenue) : 'N/A'}
                        icon={<CreditCard className="w-6 h-6" />}
                        color="purple"
                      />
                    </>
                  )}
                </div>

                {/* Charts */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  {comprehensiveData.revenue && comprehensiveData.revenue.market_penetration && (
                    <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
                      <h3 className="text-lg font-semibold text-gray-900 mb-4">Market Penetration by Room Type</h3>
                      <SimpleBarChart
                        data={comprehensiveData.revenue.market_penetration.penetration_by_room_type.map((item) => ({
                          label: item.room_type,
                          value: item.market_share,
                        }))}
                        height={200}
                      />
                    </div>
                  )}

                  {comprehensiveData.financial && comprehensiveData.financial.payment_methods && (
                    <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
                      <h3 className="text-lg font-semibold text-gray-900 mb-4">Payment Methods Distribution</h3>
                      <SimplePieChart
                        data={comprehensiveData.financial.payment_methods.payment_methods.map((item) => ({
                          label: item.payment_method,
                          value: item.percentage,
                        }))}
                        size={200}
                      />
                    </div>
                  )}
                </div>

                {/* Quick Access Cards */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 lg:gap-8">
                  <div 
                    onClick={() => setActiveTab('revenue')}
                    className="group relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-green-100/50 p-8 cursor-pointer transition-all duration-300 hover:shadow-2xl hover:scale-105 hover:border-green-300/60 overflow-hidden"
                  >
                    <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-green-400/10 to-transparent rounded-bl-full"></div>
                    <div className="relative space-y-5">
                      <div className="flex items-center gap-4">
                        <div className="p-3.5 rounded-xl bg-gradient-to-br from-green-500 to-green-600 shadow-lg">
                          <DollarSign className="w-6 h-6 text-white" />
                        </div>
                        <div>
                          <h3 className="font-bold text-gray-900 text-xl mb-1">Revenue Analytics</h3>
                          <div className="h-1 w-12 bg-gradient-to-r from-green-500 to-green-600 rounded-full"></div>
                        </div>
                      </div>
                      <p className="text-gray-600 text-sm leading-relaxed">
                        RevPAR, ADR, Occupancy, Forecast, Market Penetration
                      </p>
                    </div>
                  </div>

                  <div 
                    onClick={() => setActiveTab('operational')}
                    className="group relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-orange-100/50 p-8 cursor-pointer transition-all duration-300 hover:shadow-2xl hover:scale-105 hover:border-orange-300/60 overflow-hidden"
                  >
                    <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-orange-400/10 to-transparent rounded-bl-full"></div>
                    <div className="relative space-y-5">
                      <div className="flex items-center gap-4">
                        <div className="p-3.5 rounded-xl bg-gradient-to-br from-orange-500 to-orange-600 shadow-lg">
                          <Activity className="w-6 h-6 text-white" />
                        </div>
                        <div>
                          <h3 className="font-bold text-gray-900 text-xl mb-1">Operational Analytics</h3>
                          <div className="h-1 w-12 bg-gradient-to-r from-orange-500 to-orange-600 rounded-full"></div>
                        </div>
                      </div>
                      <p className="text-gray-600 text-sm leading-relaxed">
                        Staff Performance, Service Usage, Efficiency Metrics
                      </p>
                    </div>
                  </div>

                  <div 
                    onClick={() => setActiveTab('guest')}
                    className="group relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-purple-100/50 p-8 cursor-pointer transition-all duration-300 hover:shadow-2xl hover:scale-105 hover:border-purple-300/60 overflow-hidden"
                  >
                    <div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-br from-purple-400/10 to-transparent rounded-bl-full"></div>
                    <div className="relative space-y-5">
                      <div className="flex items-center gap-4">
                        <div className="p-3.5 rounded-xl bg-gradient-to-br from-purple-500 to-purple-600 shadow-lg">
                          <Users className="w-6 h-6 text-white" />
                        </div>
                        <div>
                          <h3 className="font-bold text-gray-900 text-xl mb-1">Guest Analytics</h3>
                          <div className="h-1 w-12 bg-gradient-to-r from-purple-500 to-purple-600 rounded-full"></div>
                        </div>
                      </div>
                      <p className="text-gray-600 text-sm leading-relaxed">
                        LTV, CAC, Repeat Rate, Satisfaction Trends
                      </p>
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                <EmptyState
                  title="No Analytics Data"
                  description="Click refresh to load analytics data"
                  action={{
                    label: 'Refresh',
                    onClick: fetchComprehensive
                  }}
                />
              </div>
            )}
          </div>
        )}

        {/* Revenue Analytics Tab */}
        {activeTab === 'revenue' && (
          <RevenueAnalyticsView
            revparData={revparData ?? undefined}
            adrData={adrData ?? undefined}
            occupancyData={occupancyData ?? undefined}
            forecastData={forecastData ?? undefined}
            marketPenetrationData={marketPenetrationData ?? undefined}
            formatCurrency={formatCurrency}
            loading={revparLoading || adrLoading || occupancyLoading || forecastLoading || marketLoading}
          />
        )}

        {/* Operational Analytics Tab */}
        {activeTab === 'operational' && (
          <OperationalAnalyticsView
            staffPerformanceData={staffPerformanceData ?? undefined}
            serviceUsageData={serviceUsageData ?? undefined}
            efficiencyData={efficiencyData ?? undefined}
            formatCurrency={formatCurrency}
            loading={staffLoading || serviceLoading || efficiencyLoading}
          />
        )}

        {/* Guest Analytics Tab */}
        {activeTab === 'guest' && (
          <GuestAnalyticsView
            ltvData={ltvData ?? undefined}
            repeatRateData={repeatRateData ?? undefined}
            satisfactionData={satisfactionData ?? undefined}
            formatCurrency={formatCurrency}
            loading={ltvLoading || repeatLoading || satisfactionLoading}
          />
        )}

        {/* Financial Analytics Tab */}
        {activeTab === 'financial' && (
          <FinancialAnalyticsView
            profitLossData={profitLossData ?? undefined}
            paymentMethodData={paymentMethodData ?? undefined}
            refundData={refundData ?? undefined}
            formatCurrency={formatCurrency}
            loading={profitLossLoading || paymentMethodLoading || refundLoading}
          />
        )}

        {}
        {activeTab === 'reports' && (
          <div className="space-y-8">
            {reportsLoading && !reportData ? (
              <Loading fullScreen text="Loading reports..." />
            ) : reportsError && !reportData ? (
              <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                <EmptyState
                  title="Unable to Load Reports"
                  description={reportsError.message || 'Something went wrong. Please try again.'}
                  action={{
                    label: 'Retry',
                    onClick: refetchReports
                  }}
                />
              </div>
            ) : (
              <>
                {}
                <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                  <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
                    <div className="space-y-3">
                      <div className="flex items-center gap-3">
                        <div className="p-2.5 rounded-xl bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
                          <FileText className="w-6 h-6 text-blue-600" />
                        </div>
                        <h2 className="text-3xl font-extrabold text-gray-900">Reports & Analytics</h2>
                      </div>
                      <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                        View comprehensive reports and statistics for bookings, revenue, and performance
                      </p>
                    </div>
                    <ExportButton
                      data={reportData ? [
                        {
                          'Total Bookings': reportData.total_bookings || 0,
                          'Total Revenue': reportData.total_revenue || 0,
                          'Total Customers': reportData.total_customers || 0,
                          'Available Rooms': reportData.available_rooms || 0,
                          'Occupied Rooms': reportData.occupied_rooms || 0,
                          'Date Range': `${dateRange.from || 'All'} to ${dateRange.to || 'All'}`
                        },
                        ...(reportData.revenue_by_date?.map(r => ({
                          'Date': r.date,
                          'Revenue': r.revenue,
                          'Bookings': r.bookings
                        })) || []),
                        ...(reportData.top_rooms?.map(r => ({
                          'Room ID': r.room_id,
                          'Room Number': r.room_number,
                          'Bookings': r.bookings,
                          'Revenue': r.revenue
                        })) || []),
                        ...(reportData.service_usage?.map(s => ({
                          'Service ID': s.service_id,
                          'Service Name': s.service_name,
                          'Usage Count': s.usage_count,
                          'Total Revenue': s.total_revenue
                        })) || [])
                      ] : []}
                      filename="financial-reports"
                      title="Financial Reports & Analytics"
                    />
                  </div>
                </div>

                {}
                <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                  <div className="flex items-center gap-3 mb-6">
                    <div className="p-2 rounded-xl bg-gradient-to-br from-amber-500/10 to-amber-600/10 border border-amber-200/40">
                      <Filter className="w-5 h-5 text-amber-600" />
                    </div>
                    <h3 className="text-xl font-bold text-gray-900">Filters</h3>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-900">From Date</label>
                      <input
                        type="date"
                        value={dateRange.from}
                        onChange={(e) => setDateRange({ ...dateRange, from: e.target.value })}
                        className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-all duration-200"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-900">To Date</label>
                      <input
                        type="date"
                        value={dateRange.to}
                        onChange={(e) => setDateRange({ ...dateRange, to: e.target.value })}
                        className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-all duration-200"
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-900">Report Type</label>
                      <select
                        value={reportType}
                        onChange={(e) => setReportType(e.target.value as 'daily' | 'weekly' | 'monthly' | 'yearly' | '')}
                        className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-blue-500/50 focus:border-blue-500 transition-all duration-200"
                      >
                        <option value="">All</option>
                        <option value="daily">Daily</option>
                        <option value="weekly">Weekly</option>
                        <option value="monthly">Monthly</option>
                        <option value="yearly">Yearly</option>
                      </select>
                    </div>
                    <div className="flex items-end">
                      <button
                        onClick={handleFilter}
                        className="w-full px-6 py-3 bg-gradient-to-r from-amber-500 to-amber-600 text-white font-semibold rounded-xl shadow-lg shadow-amber-500/30 hover:shadow-xl hover:shadow-amber-500/40 transition-all duration-300 hover:scale-105"
                      >
                        Apply Filters
                      </button>
                    </div>
                  </div>
                </div>

                {reportData && (
                  <>
                    {}
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                      {[
                        { icon: Calendar, label: 'Total Bookings', value: reportData.total_bookings || 0, color: 'blue', border: 'border-blue-500' },
                        { icon: CurrencyIcon, label: 'Total Revenue', value: formatCurrency(reportData.total_revenue || 0), color: 'emerald', border: 'border-emerald-500' },
                        { icon: Users, label: 'Total Customers', value: reportData.total_customers || 0, color: 'purple', border: 'border-purple-500' },
                        { icon: Hotel, label: 'Available Rooms', value: reportData.available_rooms || 0, color: 'orange', border: 'border-orange-500', subtitle: `${reportData.occupied_rooms || 0} occupied` },
                      ].map(({ icon: Icon, label, value, color, border, subtitle }) => {
                        const colorClassesMap = {
                          blue: { bg: 'bg-blue-100', text: 'text-blue-600', gradient: 'from-blue-500 to-blue-600' },
                          emerald: { bg: 'bg-emerald-100', text: 'text-emerald-600', gradient: 'from-emerald-500 to-emerald-600' },
                          purple: { bg: 'bg-purple-100', text: 'text-purple-600', gradient: 'from-purple-500 to-purple-600' },
                          orange: { bg: 'bg-orange-100', text: 'text-orange-600', gradient: 'from-orange-500 to-orange-600' },
                        } as const;
                        const colorClasses = colorClassesMap[color as keyof typeof colorClassesMap] || colorClassesMap.blue;

                        return (
                          <div key={label} className={`relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border-l-4 ${border} p-6 hover:shadow-2xl transition-all duration-300`}>
                            <div className="flex items-center justify-between mb-4">
                              <div className={`p-3 rounded-xl ${colorClasses.bg}`}>
                                {Icon === CurrencyIcon ? (
                                  <CurrencyIcon className={colorClasses.text} size={24} />
                                ) : (
                                  <Icon className={`w-6 h-6 ${colorClasses.text}`} />
                                )}
                              </div>
                              <TrendingUp className="w-5 h-5 text-emerald-500" />
                            </div>
                            <h3 className="text-gray-500 text-sm font-medium mb-2">{label}</h3>
                            <p className={`text-3xl font-extrabold bg-gradient-to-r ${colorClasses.gradient} bg-clip-text text-transparent`}>
                              {value}
                            </p>
                            {subtitle && (
                              <p className="text-sm text-gray-500 mt-2">{subtitle}</p>
                            )}
                          </div>
                        );
                      })}
                    </div>

                    {}
                    {reportData.bookings_by_status && (
                      <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                        <div className="flex items-center gap-3 mb-6">
                          <div className="p-2 rounded-xl bg-gradient-to-br from-purple-500/10 to-pink-500/10 border border-purple-200/40">
                            <PieChart className="w-5 h-5 text-purple-600" />
                          </div>
                          <h2 className="text-2xl font-bold text-gray-900">Bookings by Status</h2>
                        </div>
                        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                          {Object.entries(reportData.bookings_by_status).map(([status, count]) => (
                            <div key={status} className="text-center p-5 bg-gradient-to-br from-gray-50 to-white rounded-xl border border-gray-200/50 hover:shadow-lg transition-all duration-200">
                              <p className="text-3xl font-extrabold text-gray-900">{count}</p>
                              <p className="text-sm text-gray-600 capitalize mt-2 font-medium">{status.replace('_', ' ')}</p>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {}
                    {reportData.revenue_by_date && reportData.revenue_by_date.length > 0 && (
                      <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                        <div className="flex items-center gap-3 mb-6">
                          <div className="p-2 rounded-xl bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
                            <BarChart3 className="w-5 h-5 text-blue-600" />
                          </div>
                          <h2 className="text-2xl font-bold text-gray-900">Revenue by Date</h2>
                        </div>
                        <div className="overflow-x-auto">
                          <table className="w-full">
                            <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                              <tr>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Date</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Bookings</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Revenue</th>
                              </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                              {reportData.revenue_by_date.map((item, index) => (
                                <tr key={index} className="hover:bg-gray-50 transition-colors">
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                    {formatDate(new Date(item.date), 'short')}
                                  </td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{item.bookings}</td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">{formatCurrency(item.revenue)}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}

                    {}
                    {reportData.top_rooms && reportData.top_rooms.length > 0 && (
                      <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                        <h2 className="text-2xl font-bold text-gray-900 mb-6">Top Performing Rooms</h2>
                        <div className="overflow-x-auto">
                          <table className="w-full">
                            <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                              <tr>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Room Number</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Bookings</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Revenue</th>
                              </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                              {reportData.top_rooms.map((room) => (
                                <tr key={room.room_id} className="hover:bg-gray-50 transition-colors">
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">{room.room_number}</td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{room.bookings}</td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">{formatCurrency(room.revenue)}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}

                    {}
                    {reportData.service_usage && reportData.service_usage.length > 0 && (
                      <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                        <h2 className="text-2xl font-bold text-gray-900 mb-6">Service Usage</h2>
                        <div className="overflow-x-auto">
                          <table className="w-full">
                            <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                              <tr>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Service Name</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Usage Count</th>
                                <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Total Revenue</th>
                              </tr>
                            </thead>
                            <tbody className="bg-white divide-y divide-gray-200">
                              {reportData.service_usage.map((service) => (
                                <tr key={service.service_id} className="hover:bg-gray-50 transition-colors">
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">{service.service_name}</td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{service.usage_count}</td>
                                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900">{formatCurrency(service.total_revenue)}</td>
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </>
            )}
          </div>
        )}

        {}
        {activeTab === 'audit-logs' && (
          <div className="space-y-8">
            {}
            <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <div className="p-2.5 rounded-xl bg-gradient-to-br from-indigo-500/10 to-purple-500/10 border border-indigo-200/40">
                    <ClipboardList className="w-6 h-6 text-indigo-600" />
                  </div>
                  <h2 className="text-3xl font-extrabold text-gray-900">Audit Logs</h2>
                </div>
                <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                  View all system activity, user actions, and security events in real-time
                </p>
              </div>
            </div>

            {}
            <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 rounded-xl bg-gradient-to-br from-amber-500/10 to-amber-600/10 border border-amber-200/40">
                  <Filter className="w-5 h-5 text-amber-600" />
                </div>
                <h3 className="text-xl font-bold text-gray-900">Filters</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Search</label>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                    <input
                      type="text"
                      placeholder="Search actions, types..."
                      value={auditFilters.search || ''}
                      onChange={(e) => handleSearch(e.target.value)}
                      className="w-full pl-10 pr-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Action</label>
                  <input
                    type="text"
                    placeholder="Filter by action"
                    value={auditFilters.action || ''}
                    onChange={(e) => handleAuditFilterChange('action', e.target.value || undefined)}
                    className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                  />
                </div>
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Resource Type</label>
                  <input
                    type="text"
                    placeholder="Filter by type"
                    value={auditFilters.resource_type || ''}
                    onChange={(e) => handleAuditFilterChange('resource_type', e.target.value || undefined)}
                    className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                  />
                </div>
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Status</label>
                  <select
                    value={auditFilters.status || ''}
                    onChange={(e) => handleAuditFilterChange('status', e.target.value || undefined)}
                    className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                  >
                    <option value="">All</option>
                    <option value="success">Success</option>
                    <option value="failed">Failed</option>
                    <option value="error">Error</option>
                  </select>
                </div>
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Start Date</label>
                  <input
                    type="date"
                    value={auditFilters.start_date || ''}
                    onChange={(e) => handleAuditFilterChange('start_date', e.target.value || undefined)}
                    className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                  />
                </div>
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">End Date</label>
                  <input
                    type="date"
                    value={auditFilters.end_date || ''}
                    onChange={(e) => handleAuditFilterChange('end_date', e.target.value || undefined)}
                    className="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition-all duration-200"
                  />
                </div>
              </div>
            </div>

            {}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium mb-1">Total Logs</p>
                    <p className="text-3xl font-extrabold text-gray-900">{totalItems}</p>
                  </div>
                  <div className="p-3 rounded-xl bg-gradient-to-br from-indigo-500/10 to-purple-500/10 border border-indigo-200/40">
                    <FileText className="w-8 h-8 text-indigo-600" />
                  </div>
                </div>
              </div>
              <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600 font-medium mb-1">Current Page</p>
                    <p className="text-3xl font-extrabold text-gray-900">{currentPage}</p>
                  </div>
                  <div className="p-3 rounded-xl bg-gradient-to-br from-blue-500/10 to-indigo-500/10 border border-blue-200/40">
                    <Activity className="w-8 h-8 text-blue-600" />
                  </div>
                </div>
              </div>
            </div>

            {}
            {auditLoading && logs.length === 0 ? (
              <Loading fullScreen text="Loading audit logs..." />
            ) : logs.length === 0 ? (
              <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                <EmptyState
                  title="No Audit Logs Found"
                  description="No audit logs match your current filters."
                />
              </div>
            ) : (
              <>
                <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                      <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                        <tr>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">ID</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Action</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Resource</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">User</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Status</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">IP Address</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Date</th>
                          <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="bg-white divide-y divide-gray-200">
                        {logs.map((log) => (
                          <tr key={log.id} className="hover:bg-gray-50 transition-colors">
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">#{log.id}</td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900">{log.action}</td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="text-sm font-medium text-gray-900">{log.resource_type}</div>
                              {log.resource_id && (
                                <div className="text-xs text-gray-500">ID: {log.resource_id}</div>
                              )}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              {log.user ? (
                                <div>
                                  <div className="text-sm font-medium text-gray-900">{log.user.full_name}</div>
                                  <div className="text-xs text-gray-500">{log.user.email}</div>
                                </div>
                              ) : (
                                <span className="text-sm text-gray-400">System</span>
                              )}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap">
                              <div className="flex items-center gap-2">
                                {getStatusIcon(log.status)}
                                <span className={getStatusBadge(log.status)}>{log.status}</span>
                              </div>
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 font-mono">{log.ip_address || '-'}</td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600">{formatDate(log.created_at)}</td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                              <button
                                onClick={() => handleViewDetails(log)}
                                className="text-indigo-600 hover:text-indigo-700 flex items-center gap-1 font-semibold hover:underline transition-colors"
                              >
                                <Eye className="w-4 h-4" />
                                View
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>

                {}
                {totalPages > 1 && (
                  <div className="flex justify-center">
                    <Pagination
                      currentPage={currentPage}
                      totalPages={totalPages}
                      onPageChange={setCurrentPage}
                    />
                  </div>
                )}
              </>
            )}
          </div>
        )}

        {}
        {activeTab === 'reviews' && (
          <div className="space-y-8">
            {}
            <div className="bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
              <div className="space-y-3">
                <div className="flex items-center gap-3">
                  <div className="p-2.5 rounded-xl bg-gradient-to-br from-amber-500/10 to-yellow-500/10 border border-amber-200/40">
                    <Star className="w-6 h-6 text-amber-600 fill-amber-600" />
                  </div>
                  <h2 className="text-3xl font-extrabold text-gray-900">Review Management</h2>
                </div>
                <p className="text-gray-600 text-base max-w-2xl leading-relaxed">
                  Approve and manage customer reviews and ratings
                </p>
              </div>
            </div>

            {}
            <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 rounded-xl bg-gradient-to-br from-amber-500/10 to-amber-600/10 border border-amber-200/40">
                  <Filter className="w-5 h-5 text-amber-600" />
                </div>
                <h3 className="text-xl font-bold text-gray-900">Filters</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <label className="block text-sm font-semibold text-gray-900">Status</label>
                  <select
                    value={reviewsFilters.status}
                    onChange={(e) => setReviewsFilters({ ...reviewsFilters, status: e.target.value })}
                    className="w-full px-4 py-3 bg-white border-2 border-gray-200 rounded-xl focus:border-amber-400 focus:ring-4 focus:ring-amber-100 transition-all duration-200 text-gray-700 font-medium shadow-sm hover:shadow-md cursor-pointer"
                  >
                    <option value="">All statuses</option>
                    <option value="pending">Pending</option>
                    <option value="approved">Approved</option>
                    <option value="rejected">Rejected</option>
                  </select>
                </div>
                <div className="flex items-end">
                  <div className="w-full px-4 py-3 bg-gradient-to-r from-gray-50 to-white border-2 border-gray-200 rounded-xl">
                    <span className="text-sm font-semibold text-gray-700">
                      {reviewsTotalItems} review{reviewsTotalItems !== 1 ? 's' : ''}
                    </span>
                  </div>
                </div>
              </div>
            </div>

            {}
            {reviewsLoading && reviews.length === 0 ? (
              <Loading fullScreen text="Loading reviews..." />
            ) : reviews.length === 0 ? (
              <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 p-8">
                <EmptyState
                  title="No Reviews Found"
                  description="No reviews match your current filters."
                />
              </div>
            ) : (
              <>
                <div className="relative bg-white/90 backdrop-blur-xl rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-gray-200">
                      <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                        <tr>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">User</th>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Room</th>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Rating</th>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Comment</th>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Created Date</th>
                          <th className="px-8 py-5 text-left text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Status</th>
                          <th className="px-8 py-5 text-right text-xs font-bold text-gray-700 uppercase tracking-wider border-b border-gray-200">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="bg-white divide-y divide-gray-200">
                        {reviews.map((review) => (
                          <tr key={review.id} className="hover:bg-gray-50 transition-colors">
                            <td className="px-8 py-5 whitespace-nowrap">
                              <div className="text-sm font-semibold text-gray-900">{review.user?.name}</div>
                              {review.user?.email && (
                                <div className="text-xs text-gray-500">{review.user.email}</div>
                              )}
                            </td>
                            <td className="px-8 py-5 whitespace-nowrap">
                              <div className="text-sm font-medium text-gray-900">
                                Room {review.room?.room_number}
                              </div>
                              {review.room?.room_type?.name && (
                                <div className="text-xs text-gray-500">{review.room.room_type.name}</div>
                              )}
                            </td>
                            <td className="px-8 py-5 whitespace-nowrap">
                              <div className="flex items-center gap-2">
                                {renderStars(review.rating)}
                                <span className="text-sm font-semibold text-gray-700">({review.rating})</span>
                              </div>
                            </td>
                            <td className="px-8 py-5">
                              <div className="text-sm text-gray-900 max-w-xs">{review.comment}</div>
                            </td>
                            <td className="px-8 py-5 whitespace-nowrap">
                              <div className="text-sm text-gray-600">
                                {new Date(review.created_at).toLocaleDateString('en-US', {
                                  year: 'numeric',
                                  month: 'short',
                                  day: 'numeric'
                                })}
                              </div>
                            </td>
                            <td className="px-8 py-5 whitespace-nowrap">
                              {getReviewStatusBadge(review.status)}
                            </td>
                            <td className="px-8 py-5 whitespace-nowrap text-right text-sm font-medium">
                              {review.status === 'pending' && (
                                <div className="flex items-center justify-end gap-3">
                                  <button
                                    onClick={() => handleApproveReview(review.id)}
                                    className="px-4 py-2 bg-gradient-to-r from-emerald-500 to-emerald-600 text-white rounded-lg hover:from-emerald-600 hover:to-emerald-700 transition-all duration-200 shadow-lg hover:shadow-xl font-semibold flex items-center gap-2"
                                    title="Approve"
                                  >
                                    <CheckCircle className="w-4 h-4" />
                                    Approve
                                  </button>
                                  <button
                                    onClick={() => handleRejectReview(review.id)}
                                    className="px-4 py-2 bg-gradient-to-r from-rose-500 to-rose-600 text-white rounded-lg hover:from-rose-600 hover:to-rose-700 transition-all duration-200 shadow-lg hover:shadow-xl font-semibold flex items-center gap-2"
                                    title="Reject"
                                  >
                                    <XCircle className="w-4 h-4" />
                                    Reject
                                  </button>
                                </div>
                              )}
                              {review.status !== 'pending' && (
                                <span className="text-gray-400 text-xs">No actions available</span>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </div>

                {}
                {reviewsTotalPages > 1 && (
                  <div className="flex justify-center">
                    <Pagination
                      currentPage={reviewsCurrentPage}
                      totalPages={reviewsTotalPages}
                      onPageChange={setReviewsCurrentPage}
                      totalItems={reviewsTotalItems}
                      itemsPerPage={reviewsPerPage}
                    />
                  </div>
                )}
              </>
            )}
          </div>
        )}

        {}
        {showDetails && selectedLog && (
          <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl max-w-3xl w-full max-h-[90vh] overflow-y-auto shadow-2xl border border-gray-200">
              <div className="p-8">
                <div className="flex justify-between items-center mb-6">
                  <h2 className="text-3xl font-extrabold text-gray-900">Audit Log Details</h2>
                  <button
                    onClick={() => setShowDetails(false)}
                    className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-xl transition-colors"
                  >
                    <X className="w-6 h-6" />
                  </button>
                </div>

                <div className="space-y-6">
                  <div className="grid grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">ID</label>
                      <p className="text-sm text-gray-900 font-medium">#{selectedLog.id}</p>
                    </div>
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">Status</label>
                      <div className="flex items-center gap-2">
                        {getStatusIcon(selectedLog.status)}
                        <span className={getStatusBadge(selectedLog.status)}>{selectedLog.status}</span>
                      </div>
                    </div>
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">Action</label>
                      <p className="text-sm text-gray-900 font-medium">{selectedLog.action}</p>
                    </div>
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">Resource Type</label>
                      <p className="text-sm text-gray-900 font-medium">{selectedLog.resource_type}</p>
                    </div>
                    {selectedLog.resource_id && (
                      <div className="space-y-2">
                        <label className="block text-sm font-semibold text-gray-700">Resource ID</label>
                        <p className="text-sm text-gray-900 font-medium">{selectedLog.resource_id}</p>
                      </div>
                    )}
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">Date</label>
                      <p className="text-sm text-gray-900 font-medium">{formatDate(selectedLog.created_at)}</p>
                    </div>
                    {selectedLog.user && (
                      <>
                        <div className="space-y-2">
                          <label className="block text-sm font-semibold text-gray-700">User</label>
                          <p className="text-sm text-gray-900 font-medium">{selectedLog.user.full_name}</p>
                          <p className="text-xs text-gray-500">{selectedLog.user.email}</p>
                        </div>
                        <div className="space-y-2">
                          <label className="block text-sm font-semibold text-gray-700">User ID</label>
                          <p className="text-sm text-gray-900 font-medium">{selectedLog.user_id}</p>
                        </div>
                      </>
                    )}
                    {selectedLog.ip_address && (
                      <div className="space-y-2">
                        <label className="block text-sm font-semibold text-gray-700">IP Address</label>
                        <p className="text-sm text-gray-900 font-mono font-medium">{selectedLog.ip_address}</p>
                      </div>
                    )}
                    {selectedLog.request_id && (
                      <div className="space-y-2">
                        <label className="block text-sm font-semibold text-gray-700">Request ID</label>
                        <p className="text-sm text-gray-900 font-mono text-xs">{selectedLog.request_id}</p>
                      </div>
                    )}
                  </div>

                  {selectedLog.user_agent && (
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">User Agent</label>
                      <p className="text-sm text-gray-900 break-all bg-gray-50 p-3 rounded-xl">{selectedLog.user_agent}</p>
                    </div>
                  )}

                  {selectedLog.error_message && (
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-red-700">Error Message</label>
                      <p className="text-sm text-red-900 bg-red-50 p-3 rounded-xl border border-red-200">{selectedLog.error_message}</p>
                    </div>
                  )}

                  {selectedLog.details && (
                    <div className="space-y-2">
                      <label className="block text-sm font-semibold text-gray-700">Details</label>
                      <pre className="text-sm text-gray-900 bg-gray-50 p-4 rounded-xl overflow-x-auto border border-gray-200">
                        {JSON.stringify(selectedLog.details, null, 2)}
                      </pre>
                    </div>
                  )}
                </div>

                <div className="mt-8 flex justify-end">
                  <button
                    onClick={() => setShowDetails(false)}
                    className="px-6 py-3 bg-gradient-to-r from-gray-200 to-gray-300 text-gray-800 font-semibold rounded-xl hover:from-gray-300 hover:to-gray-400 transition-all duration-200 shadow-lg"
                  >
                    Close
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Custom Report Builder Modal */}
        {showReportBuilder && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <div className="max-w-4xl w-full max-h-[90vh] overflow-y-auto">
              <CustomReportBuilder onClose={() => setShowReportBuilder(false)} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Revenue Analytics View Component
const RevenueAnalyticsView: React.FC<{
  revparData?: RevPARData;
  adrData?: ADRData;
  occupancyData?: OccupancyRateData;
  forecastData?: RevenueForecastData;
  marketPenetrationData?: MarketPenetrationData;
  formatCurrency: (amount: number) => string;
  loading: boolean;
}> = ({ revparData, adrData, occupancyData, forecastData, marketPenetrationData, formatCurrency, loading }) => {
  if (loading) {
    return <Loading fullScreen text="Loading revenue analytics..." />;
  }

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {revparData && (
          <KPICard
            title="RevPAR"
            value={formatCurrency(revparData.revpar)}
            subtitle={`${revparData.period_days} days`}
            icon={<TrendingUp className="w-6 h-6" />}
            color="blue"
          />
        )}
        {adrData && (
          <KPICard
            title="ADR"
            value={formatCurrency(adrData.adr)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
        )}
        {occupancyData && (
          <KPICard
            title="Occupancy Rate"
            value={`${occupancyData.occupancy_rate.toFixed(1)}%`}
            subtitle={`${occupancyData.occupied_room_nights} / ${occupancyData.available_room_nights} nights`}
            icon={<Building2 className="w-6 h-6" />}
            color="orange"
          />
        )}
      </div>

      {forecastData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Revenue Forecast (Next 30 Days)</h3>
          <SimpleLineChart
            data={forecastData.forecast.slice(0, 30).map(item => ({
              label: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
              value: item.forecasted_revenue,
            }))}
            height={200}
          />
        </div>
      )}

      {marketPenetrationData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Market Penetration by Room Type</h3>
          <SimpleBarChart
            data={marketPenetrationData.penetration_by_room_type.map((item) => ({
              label: item.room_type,
              value: item.market_share,
            }))}
            height={200}
          />
        </div>
      )}
    </div>
  );
};

// Operational Analytics View Component
const OperationalAnalyticsView: React.FC<{
  staffPerformanceData?: StaffPerformanceData;
  serviceUsageData?: ServiceUsageData;
  efficiencyData?: OperationalEfficiencyData;
  formatCurrency: (amount: number) => string;
  loading: boolean;
}> = ({ serviceUsageData, efficiencyData, formatCurrency, loading }) => {
  if (loading) {
    return <Loading fullScreen text="Loading operational analytics..." />;
  }

  return (
    <div className="space-y-6">
      {efficiencyData && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <KPICard
            title="Conversion Rate"
            value={`${efficiencyData.conversion_rate.toFixed(1)}%`}
            icon={<Target className="w-6 h-6" />}
            color="blue"
          />
          <KPICard
            title="Avg Booking Value"
            value={formatCurrency(efficiencyData.average_booking_value)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
          <KPICard
            title="Cancellation Rate"
            value={`${efficiencyData.cancellation_rate.toFixed(1)}%`}
            icon={<Activity className="w-6 h-6" />}
            color="red"
          />
        </div>
      )}

      {serviceUsageData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Top Services by Revenue</h3>
          <SimpleBarChart
            data={serviceUsageData.services.slice(0, 10).map(item => ({
              label: item.service_name,
              value: item.total_revenue,
            }))}
            height={250}
          />
        </div>
      )}
    </div>
  );
};

// Guest Analytics View Component
const GuestAnalyticsView: React.FC<{
  ltvData?: GuestLTVData;
  repeatRateData?: RepeatGuestRateData;
  satisfactionData?: GuestSatisfactionTrendsData;
  formatCurrency: (amount: number) => string;
  loading: boolean;
}> = ({ ltvData, repeatRateData, satisfactionData, formatCurrency, loading }) => {
  if (loading) {
    return <Loading fullScreen text="Loading guest analytics..." />;
  }

  return (
    <div className="space-y-6">
      {repeatRateData && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <KPICard
            title="Repeat Guest Rate"
            value={`${repeatRateData.repeat_guest_rate.toFixed(1)}%`}
            subtitle={`${repeatRateData.repeat_guests} repeat / ${repeatRateData.total_guests} total`}
            icon={<Users className="w-6 h-6" />}
            color="purple"
          />
          {ltvData && (
            <KPICard
              title="Average LTV"
              value={formatCurrency(ltvData.average_ltv)}
              subtitle={`${ltvData.total_guests_analyzed} guests`}
              icon={<Award className="w-6 h-6" />}
              color="blue"
            />
          )}
          {satisfactionData && (
            <KPICard
              title="Avg Satisfaction"
              value={`${satisfactionData.overall_average_rating.toFixed(1)}/5`}
              subtitle={`${satisfactionData.total_reviews} reviews`}
              icon={<Star className="w-6 h-6" />}
              color="orange"
            />
          )}
        </div>
      )}

      {satisfactionData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Satisfaction Trends</h3>
          <SimpleLineChart
            data={satisfactionData.trends.map(item => ({
              label: new Date(item.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
              value: item.average_rating,
            }))}
            height={200}
          />
        </div>
      )}
    </div>
  );
};

// Financial Analytics View Component
const FinancialAnalyticsView: React.FC<{
  profitLossData?: ProfitLossData;
  paymentMethodData?: PaymentMethodAnalyticsData;
  refundData?: RefundAnalysisData;
  formatCurrency: (amount: number) => string;
  loading: boolean;
}> = ({ profitLossData, paymentMethodData, formatCurrency, loading }) => {
  if (loading) {
    return <Loading fullScreen text="Loading financial analytics..." />;
  }

  return (
    <div className="space-y-6">
      {profitLossData && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <KPICard
            title="Total Revenue"
            value={formatCurrency(profitLossData.total_revenue)}
            icon={<DollarSign className="w-6 h-6" />}
            color="green"
          />
          <KPICard
            title="Refunds"
            value={formatCurrency(profitLossData.refunds)}
            icon={<Download className="w-6 h-6" />}
            color="red"
          />
          <KPICard
            title="Net Revenue"
            value={formatCurrency(profitLossData.net_revenue)}
            icon={<TrendingUp className="w-6 h-6" />}
            color="blue"
          />
          <KPICard
            title="Gross Profit"
            value={formatCurrency(profitLossData.gross_profit)}
            icon={<Award className="w-6 h-6" />}
            color="purple"
          />
        </div>
      )}

      {paymentMethodData && (
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Payment Methods Distribution</h3>
          <SimplePieChart
            data={paymentMethodData.payment_methods.map((item) => ({
              label: item.payment_method,
              value: item.percentage,
            }))}
            size={250}
          />
        </div>
      )}
    </div>
  );
};

export default AnalyticsDashboardPage;

