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, Receipt, Heart, CreditCard } from 'lucide-react';
import { toast } from 'sonner';
import TransactionHistory from '../components/TransactionHistory';
import MemberBadge from '@/components/MemberBadge';
import useMemberTiers from '../hooks/use-member-tiers'

const Dashboard = () => {
  const { user, resendVerificationEmail, refreshUser } = useAuth();
  const [events, setEvents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [resendLoading, setResendLoading] = useState(false);
  const [eventActivity, setEventActivity] = useState(null);
  const [activityLoading, setActivityLoading] = useState(true);
  const [transactionsLoading, setTransactionsLoading] = useState(true);
  const [transactions, setTransactions] = useState({ subscriptions: [], donations: [] });
  const [activeTransactionTab, setActiveTransactionTab] = useState('all');
  const joinedDate = user?.member_since || user?.created_at;
  const { tiers, loading: tiersLoading } = useMemberTiers();

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

  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 fetchEventActivity = async () => {
    try {
      const response = await api.get('/members/event-activity');
      setEventActivity(response.data);
    } catch (error) {
      console.error('Failed to fetch event activity:', error);
    } finally {
      setActivityLoading(false);
    }
  };

  const fetchTransactions = async () => {
    try {
      setTransactionsLoading(true);
      const response = await api.get('/members/transactions');
      setTransactions(response.data);
    } catch (error) {
      console.error('Failed to load transactions:', error);
      // Don't show error toast - transactions are optional
    } finally {
      setTransactionsLoading(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_validation: { icon: Clock, label: 'Pending Validation', className: 'bg-gray-200 text-gray-700' },
      pre_validated: { icon: CheckCircle, label: 'Pre-Validated', className: 'bg-[var(--green-light)] text-white' },
      payment_pending: { icon: AlertCircle, label: 'Payment Pending', className: 'bg-orange-500 text-white' },
      active: { icon: CheckCircle, label: 'Active', className: 'bg-[var(--green-light)] text-white' },
      inactive: { icon: AlertCircle, label: 'Inactive', className: 'bg-gray-400 text-white' },
      canceled: { icon: AlertCircle, label: 'Canceled', className: 'bg-red-100 text-red-700' },
      expired: { icon: Clock, label: 'Expired', className: 'bg-red-500 text-white' },
      abandoned: { icon: AlertCircle, label: 'Abandoned', className: 'bg-gray-300 text-gray-600' }
    };

    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_validation: 'Your application is under review by our admin team.',
      pre_validated: '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.',
      canceled: 'Your membership has been canceled. Contact us to rejoin.',
      expired: 'Your membership has expired. Please renew to regain access.',
      abandoned: 'Your application was not completed. Contact us to restart the process.'
    };

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



  return (
    <div className="min-h-screen bg-gradient-to-b from-[var(--neutral-100)] to-[var(--neutral-800)]">
      <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-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Welcome Back, {user?.first_name}!
          </h1>
          <p className="text-lg text-brand-purple " 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-[var(--lavender-300)] border-2 border-brand-purple  mb-8">
            <div className="flex items-start gap-4">
              <AlertCircle className="h-6 w-6 text-brand-purple  flex-shrink-0 mt-1" />
              <div className="flex-1">
                <h3 className="text-lg font-semibold text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                  Verify Your Email Address
                </h3>
                <p className="text-brand-purple  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-brand-purple  text-brand-purple  hover:bg-brand-purple  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-background rounded-2xl border border-[var(--neutral-800)] 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-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                Membership Status
              </h2>
              <div className="mb-4">
                {getStatusBadge(user?.status)}
              </div>
              <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                {getStatusMessage(user?.status)}
              </p>
            </div>
            <Link to="/profile">
              <Button
                className="btn-lavender"
                data-testid="view-profile-button"
              >
                <User className="h-4 w-4 mr-2" />
                Edit Profile
              </Button>
            </Link>
          </div>
        </Card>

        {/* Grid Layout */}
        <div className="grid lg:grid-cols-2 gap-8">
          {/* Quick Stats */}
          <div className='space-y-8'>

            <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)]" data-testid="quick-stats-card">
              <h3 className="text-xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Quick Info
              </h3>
              <div className="space-y-4">
                {/* member date and badge */}
                <div className='flex justify-between'>
                  <div>
                    <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Member Since</p>
                    <p className="text-[var(--purple-ink)] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                      {joinedDate ? new Date(joinedDate).toLocaleDateString() : 'N/A'}
                    </p>
                  </div>
                  {!tiersLoading && (
                    <div className='lg:mr-10'>
                    <MemberBadge memberSince={joinedDate} tiers={tiers} />
                    </div>
                  )}
                </div>
                {/* email */}
                <div>
                  <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Email</p>
                  <p className="text-[var(--purple-ink)] font-medium" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user?.email}</p>
                </div>
                {/* role */}
                <div>
                  <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Role</p>
                  <p className="text-[var(--purple-ink)] font-medium capitalize" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{user?.role}</p>
                </div>


              </div>
            </Card>
            <Card className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)]" data-testid="quick-stats-card">
              <h3 className="text-xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Membership Info
              </h3>
              <div className="space-y-4">
                {!user.subscription_end_date && !user.subscription_end_date && (
                  <div>No subscriptions yet</div>
                )}
                {user?.subscription_start_date && user?.subscription_end_date && (
                  <>
                    <div className="pt-4 border-t border-[var(--neutral-800)]">
                      <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Membership Period</p>
                      <p className="text-[var(--purple-ink)] 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-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Days Remaining</p>
                      <p className="text-[var(--purple-ink)] 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>
          </div>

          {/* Upcoming Events */}
          <Card className="lg:col-span-1 p-6 bg-background rounded-2xl border border-[var(--neutral-800)]" data-testid="upcoming-events-card">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-xl font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                My Event Activity
              </h3>
              <Link to="/events">
                <Button className="bg-[var(--purple-lavender)] text-white hover:bg-[var(--purple-muted)] rounded-full dark:hover:bg-brand-lavender dark:hover:text-brand-dark-lavender px-6">
                  <Calendar className="h-4 w-4 mr-2" />
                  Browse Events
                </Button>
              </Link>
            </div>

            {loading ? (
              <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Loading events...</p>
            ) : events.length > 0 ? (
              <div className="space-y-4 gap-4">
                {events.map((event) => (
                  <Link to={`/events/${event.id}`} key={event.id}>
                    <div
                      className="p-4 border border-[var(--neutral-800)] rounded-xl hover:border-brand-purple  hover:shadow-md transition-all cursor-pointer"
                      data-testid={`event-card-${event.id}`}
                    >
                      <div className="flex items-start gap-4">
                        <div className="bg-[var(--neutral-800)]/20 p-3 rounded-lg">
                          <Calendar className="h-6 w-6 text-brand-purple " />
                        </div>
                        <div className="flex-1">
                          <h4 className="font-semibold text-[var(--purple-ink)] mb-1" style={{ fontFamily: "'Inter', sans-serif" }}>{event.title}</h4>
                          <p className="text-sm text-brand-purple  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-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>{event.location}</p>
                        </div>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            ) : (
              <div className="text-center gap-4 py-12">
                <Calendar className="h-16 w-16 text-[var(--neutral-800)] mx-auto mb-4" />
                <p className="text-brand-purple  mb-4" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>No upcoming events at the moment.</p>
                <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>Check back later for new events!</p>
              </div>
            )}
          </Card>
        </div>

        {/* CTA Section */}
        {user?.status === 'pending_validation' && (
          <Card className="mt-8 p-8 bg-gradient-to-br from-[var(--neutral-800)]/20 to-[var(--lavender-300)]/20 rounded-2xl border border-[var(--neutral-800)]">
            <div className="text-center">
              <h3 className="text-2xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Application Under Review
              </h3>
              <p className="text-brand-purple  mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Your membership application is being reviewed by our admin team. You'll be notified once validated!
              </p>
            </div>
          </Card>
        )}

        {/* Payment Prompt for payment_pending status */}
        {user?.status === 'payment_pending' && (
          <Card className="mt-8 p-8 bg-gradient-to-br from-[var(--neutral-800)]/20 to-[var(--lavender-300)]/20 rounded-2xl border-2 border-brand-purple ">
            <div className="text-center">
              <div className="mb-4">
                <AlertCircle className="h-16 w-16 text-brand-purple  mx-auto" />
              </div>
              <h3 className="text-2xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                Complete Your Payment
              </h3>
              <p className="text-brand-purple  mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Great news! Your membership application has been validated. Complete your payment to activate your membership and gain full access to all member benefits.
              </p>
              <Link to="/plans">
                <Button
                  className="bg-[var(--neutral-800)] text-[var(--purple-ink)] hover:bg-background 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>
        )}

        {/* Transaction History Section */}
        <div className="mt-8">
          <TransactionHistory
            subscriptions={transactions.subscriptions}
            donations={transactions.donations}
            totalSubscriptionCents={transactions.total_subscription_amount_cents}
            totalDonationCents={transactions.total_donation_amount_cents}
            loading={transactionsLoading}
            isAdmin={false}
          />
        </div>

      </div>
      <MemberFooter />
    </div>
  );
};

export default Dashboard;
