import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../utils/api';
import { Card } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Badge } from '../components/ui/badge';
import Navbar from '../components/Navbar';
import MemberFooter from '../components/MemberFooter';
import { Calendar, User, CheckCircle, Clock, AlertCircle, Mail, Users, Image, FileText, DollarSign, Scale } from 'lucide-react';
import { toast } from 'sonner';

const Dashboard = () => {
  const { user, resendVerificationEmail, refreshUser } = useAuth();
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [resendLoading, setResendLoading] = useState(false);

  useEffect(() => {
    fetchUpcomingEvents();
  }, []);

  const fetchUpcomingEvents = async () => {
    try {
      const response = await api.get('/events');
      const upcomingEvents = response.data.slice(0, 3);
      setEvents(upcomingEvents);
    } catch (error) {
      console.error('Failed to fetch events:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleResendVerification = async () => {
    setResendLoading(true);
    try {
      await resendVerificationEmail();
      toast.success('Verification email sent! Please check your inbox.');
    } catch (error) {
      const errorMessage = error.response?.data?.detail || 'Failed to send verification email';

      // If email is already verified, refresh user data to update UI
      if (errorMessage === 'Email is already verified') {
        try {
          await refreshUser();
          toast.success('Your email is already verified!');
        } catch (refreshError) {
          toast.error('Email is already verified. Please refresh the page.');
        }
      } else {
        toast.error(errorMessage);
      }
    } finally {
      setResendLoading(false);
    }
  };

  const getStatusBadge = (status) => {
    const statusConfig = {
      pending_email: { icon: Clock, label: 'Pending Email', className: 'bg-orange-100 text-orange-700' },
      pending_approval: { icon: Clock, label: 'Pending Approval', className: 'bg-gray-200 text-gray-700' },
      pre_approved: { icon: CheckCircle, label: 'Pre-Approved', className: 'bg-[#81B29A] text-white' },
      payment_pending: { icon: AlertCircle, label: 'Payment Pending', className: 'bg-orange-500 text-white' },
      active: { icon: CheckCircle, label: 'Active', className: 'bg-[#81B29A] text-white' },
      inactive: { icon: AlertCircle, label: 'Inactive', className: 'bg-gray-400 text-white' }
    };

    const config = statusConfig[status] || statusConfig.inactive;
    const Icon = config.icon;

    return (
      <Badge className={`${config.className} px-4 py-2 rounded-full flex items-center gap-2`}>
        <Icon className="h-4 w-4" />
        {config.label}
      </Badge>
    );
  };

  const getStatusMessage = (status) => {
    const messages = {
      pending_email: 'Please check your email to verify your account.',
      pending_approval: 'Your application is under review by our admin team.',
      pre_approved: 'Your application is under review by our admin team.',
      payment_pending: 'Please complete your payment to activate your membership.',
      active: 'Your membership is active! Enjoy all member benefits.',
      inactive: 'Your membership is currently inactive.'
    };

    return messages[status] || '';
  };

  return (
    <div className="min-h-screen bg-white">
      <Navbar />

      <div className="max-w-7xl mx-auto px-6 py-12">
        {/* Welcome Section */}
        <div className="mb-12">
          <h1 className="text-4xl md:text-5xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Welcome Back, {user?.first_name}!
          </h1>
          <p className="text-lg text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Here's an overview of your membership status and upcoming events.
          </p>
        </div>

        {/* Email Verification Alert */}
        {user && !user.email_verified && (
          <Card className="p-6 bg-[#f1eef9] border-2 border-[#664fa3] mb-8">
            <div className="flex items-start gap-4">
              <AlertCircle className="h-6 w-6 text-[#664fa3] flex-shrink-0 mt-1" />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-[#422268] mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                  Verify Your Email Address
                </h3>
                <p className="text-[#664fa3] mb-4" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Please verify your email address to complete your registration.
                  Check your inbox for the verification link.
                </p>
                <Button
                  onClick={handleResendVerification}
                  disabled={resendLoading}
                  variant="outline"
                  className="border-2 border-[#664fa3] text-[#664fa3] hover:bg-[#664fa3] hover:text-white"
                >
                  <Mail className="h-4 w-4 mr-2" />
                  {resendLoading ? 'Sending...' : 'Resend Verification Email'}
                </Button>
              </div>
            </div>
          </Card>
        )}

        {/* Status Card */}
        <Card className="p-8 bg-white rounded-2xl border border-[#ddd8eb] shadow-lg mb-8" data-testid="status-card">
          <div className="flex items-start justify-between flex-wrap gap-4">
            <div>
              <h2 className="text-2xl font-semibold text-[#422268] mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                Membership Status
              </h2>
              <div className="mb-4">
                {getStatusBadge(user?.status)}
              </div>
              <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                {getStatusMessage(user?.status)}
              </p>
            </div>
            <Link to="/profile">
              <Button
                className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-6"
                data-testid="view-profile-button"
              >
                <User className="h-4 w-4 mr-2" />
                View Profile
              </Button>
            </Link>
          </div>
        </Card>

        {/* Grid Layout */}
        <div className="grid lg:grid-cols-3 gap-8">
          {/* Quick Stats */}
          <Card className="p-6 bg-white rounded-2xl border border-[#ddd8eb]" data-testid="quick-stats-card">
            <h3 className="text-xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              Quick Info
            </h3>
            <div className="space-y-4">
              <div>
                <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Email</p>
                <p className="text-[#422268] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user?.email}</p>
              </div>
              <div>
                <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Role</p>
                <p className="text-[#422268] font-medium capitalize" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user?.role}</p>
              </div>
              <div>
                <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Member Since</p>
                <p className="text-[#422268] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  {user?.created_at ? new Date(user.created_at).toLocaleDateString() : 'N/A'}
                </p>
              </div>
              {user?.subscription_start_date && user?.subscription_end_date && (
                <>
                  <div className="pt-4 border-t border-[#ddd8eb]">
                    <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Membership Period</p>
                    <p className="text-[#422268] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      {new Date(user.subscription_start_date).toLocaleDateString()} - {new Date(user.subscription_end_date).toLocaleDateString()}
                    </p>
                  </div>
                  <div>
                    <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Days Remaining</p>
                    <p className="text-[#422268] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      {Math.max(0, Math.ceil((new Date(user.subscription_end_date) - new Date()) / (1000 * 60 * 60 * 24)))} days
                    </p>
                  </div>
                </>
              )}
            </div>
          </Card>

          {/* Upcoming Events */}
          <Card className="lg:col-span-2 p-6 bg-white rounded-2xl border border-[#ddd8eb]" data-testid="upcoming-events-card">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-xl font-semibold text-[#422268]" style={{ fontFamily: "'Inter', sans-serif" }}>
                Upcoming Events
              </h3>
              <Link to="/events">
                <Button
                  variant="ghost"
                  className="text-[#ff9e77] hover:text-[#664fa3]"
                  data-testid="view-all-events-button"
                >
                  View All
                </Button>
              </Link>
            </div>

            {loading ? (
              <p className="text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading events...</p>
            ) : events.length > 0 ? (
              <div className="space-y-4">
                {events.map((event) => (
                  <Link to={`/events/${event.id}`} key={event.id}>
                    <div
                      className="p-4 border border-[#ddd8eb] rounded-xl hover:border-[#664fa3] hover:shadow-md transition-all cursor-pointer"
                      data-testid={`event-card-${event.id}`}
                    >
                      <div className="flex items-start gap-4">
                        <div className="bg-[#DDD8EB]/20 p-3 rounded-lg">
                          <Calendar className="h-6 w-6 text-[#664fa3]" />
                        </div>
                        <div className="flex-1">
                          <h4 className="font-semibold text-[#422268] mb-1" style={{ fontFamily: "'Inter', sans-serif" }}>{event.title}</h4>
                          <p className="text-sm text-[#664fa3] mb-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                            {new Date(event.start_at).toLocaleDateString()} at{' '}
                            {new Date(event.start_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                          </p>
                          <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{event.location}</p>
                        </div>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="text-center py-12">
                <Calendar className="h-16 w-16 text-[#ddd8eb] mx-auto mb-4" />
                <p className="text-[#664fa3] mb-4" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>No upcoming events at the moment.</p>
                <p className="text-sm text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Check back later for new events!</p>
              </div>
            )}
          </Card>
        </div>

        {/* CTA Section */}
        {user?.status === 'pending_approval' && (
          <Card className="mt-8 p-8 bg-gradient-to-br from-[#DDD8EB]/20 to-[#f1eef9]/20 rounded-2xl border border-[#ddd8eb]">
            <div className="text-center">
              <h3 className="text-2xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Application Under Review
              </h3>
              <p className="text-[#664fa3] mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Your membership application is being reviewed by our admin team. You'll be notified once approved!
              </p>
            </div>
          </Card>
        )}

        {/* Payment Prompt for payment_pending status */}
        {user?.status === 'payment_pending' && (
          <Card className="mt-8 p-8 bg-gradient-to-br from-[#DDD8EB]/20 to-[#f1eef9]/20 rounded-2xl border-2 border-[#664fa3]">
            <div className="text-center">
              <div className="mb-4">
                <AlertCircle className="h-16 w-16 text-[#664fa3] mx-auto" />
              </div>
              <h3 className="text-2xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Complete Your Payment
              </h3>
              <p className="text-[#664fa3] mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Great news! Your membership application has been approved. Complete your payment to activate your membership and gain full access to all member benefits.
              </p>
              <Link to="/plans">
                <Button
                  className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-8 py-6 text-lg font-semibold"
                  data-testid="complete-payment-cta"
                >
                  <CheckCircle className="mr-2 h-5 w-5" />
                  Complete Payment
                </Button>
              </Link>
            </div>
          </Card>
        )}
      </div>
      <MemberFooter />
    </div>
  );
};

export default Dashboard;
