import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { mockApi } from '@/services/mockApi';
import CounterCard from '@/components/dashboard/CounterCard';
import ApexChart from '@/components/dashboard/ApexChart';
import EnhancedDataTable from '@/components/dashboard/EnhancedDataTable';
import { useDashboardFeatures } from '@/hooks/useDashboardFeatures';
import { 
  Users, 
  TrendingUp, 
  DollarSign, 
  Eye,
  Calendar,
  MapPin,
  Star,
  CreditCard,
  CheckCircle,
  Clock,
  User,
  Plus
} from 'lucide-react';

const Dashboard = () => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { t } = useLanguage();
  const { isDarkMode, toggleDarkMode, initializeTooltips } = useDashboardFeatures();
  const [stats, setStats] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  // If user is admin/super_admin, redirect to Admin dashboard
  useEffect(() => {
    if (user?.role === 'admin' || user?.role === 'super_admin') {
      navigate('/dashboard/admin', { replace: true });
    }
  }, [user, navigate]);

  useEffect(() => {
    const fetchStats = async () => {
      try {
        setLoading(true);
        const dashboardStats = await mockApi.getDashboardStats(user?.id || '1');
        setStats(dashboardStats);
      } catch (error) {
        console.error('Error fetching dashboard stats:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
    initializeTooltips();
  }, [user, initializeTooltips]);

  // Sample data for charts
  const monthlyData = [10, 20, 15, 30, 35, 30, 45, 59, 30, 35, 25, 29, 15];
  const monthlyLabels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  // Sample data for table
  const tableColumns = [
    { key: 'guest', label: 'Guest', sortable: true },
    { key: 'listing', label: 'Listing', sortable: true },
    { key: 'date', label: 'Date', sortable: true },
    { key: 'payment', label: 'Payment', sortable: true },
    { 
      key: 'status', 
      label: 'Status', 
      render: (value: string) => (
        <span className={`badge ${
          value === 'Confirmed' ? 'bg-success' : 
          value === 'Pending' ? 'bg-warning' : 'bg-secondary'
        }`}>
          {value}
        </span>
      )
    },
    { 
      key: 'action', 
      label: 'Action', 
      render: () => (
        <button className="btn btn-outline-primary btn-sm">View</button>
      )
    }
  ];

  const sampleBookings = [
    {
      guest: 'John Doe',
      listing: 'Ocean View Villa',
      date: '2024-01-15',
      payment: '$299',
      status: 'Confirmed'
    },
    {
      guest: 'Jane Smith',
      listing: 'Mountain Cabin',
      date: '2024-01-16',
      payment: '$199',
      status: 'Pending'
    },
    {
      guest: 'Mike Johnson',
      listing: 'City Apartment',
      date: '2024-01-17',
      payment: '$149',
      status: 'Confirmed'
    }
  ];

  if (loading) {
    return (
      <div className="d-flex align-items-center justify-content-center" style={{ height: '400px' }}>
        <div className="text-center">
          <div className="spinner-border text-primary mb-3" role="status">
            <span className="visually-hidden">Loading...</span>
          </div>
          <div className="text-muted">Loading dashboard...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="mobile-safe-top lg:p-6 p-4 space-y-4 lg:space-y-6">
      {/* Header Banner */}
      <div className="mobile-card bg-gradient-to-br from-primary to-primary-glow rounded-lg p-4 lg:p-6 text-white relative overflow-hidden">
        <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between">
          <div className="flex-1">
            <h1 className="mobile-title lg:text-3xl font-bold mb-2 lg:mb-3">
              ¡Welcome back, {user?.name || 'User'}!
            </h1>
            <p className="text-white/80 text-sm lg:text-base mb-4">
              Manage your listings, track bookings, and grow your business with our comprehensive dashboard.
            </p>
            <button className="mobile-btn bg-white text-primary hover:bg-white/90 transition-colors">
              <Plus className="h-4 w-4 mr-2" />
              Add New Listing
            </button>
          </div>
          <div className="hidden lg:block">
            <img 
              src="https://img.freepik.com/foto-gratis/vista-superior-mano-sosteniendo-telefono-inteligente_23-2149617681.jpg" 
              alt="Dashboard" 
              className="w-48 h-auto opacity-80"
            />
          </div>
        </div>
      </div>

      {/* Statistics Cards */}
      <div className="mobile-grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
        <div className="mobile-card">
          <CounterCard
            icon={<Users size={20} />}
            title="Times Bookmarked"
            value={stats?.bookmarks || 847}
            suffix=""
            trend={12}
            color="#F84525"
          />
        </div>
        <div className="mobile-card">
          <CounterCard
            icon={<TrendingUp size={20} />}
            title="Progress"
            value={stats?.progress || 75}
            suffix="%"
            trend={-3}
            color="#28a745"
          />
        </div>
        <div className="mobile-card">
          <CounterCard
            icon={<DollarSign size={20} />}
            title="Revenue"
            value={stats?.revenue || 12850}
            suffix=""
            trend={18}
            color="#ffc107"
          />
        </div>
        <div className="mobile-card">
          <CounterCard
            icon={<Eye size={20} />}
            title="Visitors"
            value={stats?.visitors || 2847}
            suffix=""
            trend={7}
            color="#17a2b8"
          />
        </div>
      </div>

      {/* Charts Row */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6">
        <div className="lg:col-span-2">
          <div className="mobile-card h-full">
            <ApexChart
              type="area"
              data={monthlyData}
              labels={monthlyLabels}
              title="Monthly Statistics"
              height={300}
              color="#F84525"
            />
          </div>
        </div>
        <div className="mobile-card">
          <div className="p-4 lg:p-6">
            <h3 className="text-lg font-semibold mb-4">Performance Overview</h3>
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-muted-foreground">Booking Rate</span>
                <span className="text-primary font-bold">78%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-primary h-2 rounded-full" style={{ width: '78%' }}></div>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-muted-foreground">Customer Satisfaction</span>
                <span className="text-green-600 font-bold">92%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-green-600 h-2 rounded-full" style={{ width: '92%' }}></div>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-muted-foreground">Response Time</span>
                <span className="text-yellow-600 font-bold">65%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-yellow-600 h-2 rounded-full" style={{ width: '65%' }}></div>
              </div>

              <div className="flex justify-between items-center">
                <span className="text-sm font-medium text-muted-foreground">Revenue Growth</span>
                <span className="text-blue-600 font-bold">84%</span>
              </div>
              <div className="w-full bg-muted rounded-full h-2">
                <div className="bg-blue-600 h-2 rounded-full" style={{ width: '84%' }}></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Recent Bookings Table */}
      <div className="mobile-card">
        <div className="overflow-x-auto">
          <EnhancedDataTable
            data={sampleBookings}
            columns={tableColumns}
            itemsPerPage={5}
            searchable={true}
            exportable={true}
          />
        </div>
      </div>
    </div>
  );
};

export default Dashboard;