'use client';

import React, { useEffect, useState } from 'react';
import { motion } from 'framer-motion';
import { 
  CalendarCheck, 
  Clock,
  DollarSign,
  TrendingUp,
  Award,
  Search,
  Calendar,
  CalendarX,
  Wallet,
  Users,
  CheckCircle,
  XCircle
} from 'lucide-react';
import { useUserStore } from '../../../../store/useUserStore';

interface DashboardStats {
  totalAppointments: number;
  pendingAppointments: number;
  confirmedAppointments: number;
  cancelledAppointments: number;
  completedAppointments: number;
  noShowAppointments: number;
  totalEarnings: number;
  reservedEarnings: number;
  avgSessionAmount: number;
  totalStudents: number;
  nextAppointment: {
    id: number;
    date: string;
    startTime: string;
    endTime: string;
    status: string;
    amount: number;
    meetingLink: string;
    notes: string;
    studentName: string;
    studentEmail: string;
  } | null;
  averageResponseTime: string;
  nextPayout: number;
}

const ForeignStudentDashboardHome = () => {
  const { user } = useUserStore();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchDashboardStats();
  }, []);

  const fetchDashboardStats = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await fetch('/api/internal/foreign-student/dashboard-stats');

      console.log("Comming Response", response)
      
      if (!response.ok) {
        throw new Error('Failed to fetch dashboard statistics');
      }
      
      const data = await response.json();
      
      if (data.success) {
        setStats(data.data);
      } else {
        throw new Error(data.error || 'Failed to load data');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'An error occurred');
      console.error('Error fetching dashboard stats:', err);
    } finally {
      setLoading(false);
    }
  };

  const appointmentStats = [
    {
      label: 'Total Appointments',
      count: stats?.totalAppointments || 0,
      icon: <Calendar className="w-7 h-7" />,
      description: 'All scheduled sessions',
      color: 'blue'
    },
    {
      label: 'Pending Appointments',
      count: stats?.pendingAppointments || 0,
      icon: <Clock className="w-7 h-7" />,
      description: 'Awaiting confirmation',
      color: 'amber'
    },
    {
      label: 'Confirmed Appointments',
      count: stats?.confirmedAppointments || 0,
      icon: <CheckCircle className="w-7 h-7" />,
      description: 'Ready for sessions',
      color: 'emerald'
    },
    {
      label: 'Completed Appointments',
      count: stats?.completedAppointments || 0,
      icon: <CalendarCheck className="w-7 h-7" />,
      description: 'Finished sessions',
      color: 'green'
    }
  ];

  const earningsStats = [
    {
      label: 'Total Earnings',
      count: `$${(stats?.totalEarnings || 0)}`,
      icon: <DollarSign className="w-7 h-7" />,
      description: 'Completed session earnings',
      color: 'purple'
    },
    {
      label: 'Reserved Earnings',
      count: `$${(stats?.reservedEarnings || 0)}`,
      icon: <Wallet className="w-7 h-7" />,
      description: 'Pending payout',
      color: 'indigo'
    },
    {
      label: 'Avg. Session Rate',
      count: `$${(stats?.avgSessionAmount || 0)}`,
      icon: <TrendingUp className="w-7 h-7" />,
      description: 'Per session average',
      color: 'cyan'
    },
    {
      label: 'Total Students',
      count: stats?.totalStudents || 0,
      icon: <Users className="w-7 h-7" />,
      description: 'Unique students taught',
      color: 'violet'
    }
  ];

  const formatDateTime = (date: string, time: string) => {
  console.log('=== DEBUG DATE PARSING ===');
  console.log('Input date:', date); // Should show "2025-12-23"
  console.log('Input time:', time); // Should show time value
  
  // Just extract and format the parts we need
  const [year, month, day] = date.split('-');
  
  console.log('Split date parts:', { year, month, day });
  console.log('Day value from split:', day);
  console.log('Parsed day number:', parseInt(day));
  
  const [hours, minutes] = time.split(':').slice(0, 2);
  
  // Convert hours to 12-hour format
  const hourNum = parseInt(hours);
  const period = hourNum >= 12 ? 'PM' : 'AM';
  const displayHour = hourNum % 12 || 12; // Convert 0 to 12 for midnight
  
  // Month names for better readability
  const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'November', 'December'
  ];
  
  const monthName = monthNames[parseInt(month) - 1];
  const dayNumber = parseInt(day);
  
  console.log('Final values:', { monthName, dayNumber, displayHour, minutes, period });
  
  // Simple format: "December 23 at 9:00 PM"
  const result = `${monthName} ${dayNumber} at ${displayHour}:${minutes.padStart(2, '0')} ${period}`;
  console.log('Formatted result:', result);
  console.log('=== END DEBUG ===');
  
  return result;
};

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading dashboard data...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-center">
          <XCircle className="w-12 h-12 text-rose-500 mx-auto mb-4" />
          <p className="text-gray-800 font-medium mb-2">Error loading dashboard</p>
          <p className="text-gray-600 mb-4">{error}</p>
          <button
            onClick={fetchDashboardStats}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-10">
      {/* Welcome Header */}
      <motion.div 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center space-y-6"
      >
        {/* Premium Badge */}
        <div className="inline-flex items-center gap-2 px-4 py-2 bg-blue-50 rounded-full border border-blue-200">
          <Award className="w-4 h-4 text-blue-600" />
          <span className="text-sm font-medium text-blue-700">Appointment Management Dashboard</span>
        </div>
        
        {/* Personalized Greeting */}
        <div>
          <h1 className="text-3xl md:text-4xl font-bold text-gray-800 mb-3">
            Welcome back, <span className="text-blue-600">{user?.name || 'Student'}</span>
          </h1>
          
          <p className="text-gray-600 max-w-2xl mx-auto text-lg">
            Manage your appointments, track earnings, and review your teaching sessions in one place.
          </p>
        </div>
      </motion.div>

      {/* Appointment Statistics */}
      <div>
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
            <CalendarCheck className="w-6 h-6 text-blue-600" />
            Appointment Overview
          </h2>
          <span className="text-sm text-gray-500 px-3 py-1 bg-gray-100 rounded-full">
            Real-time data
          </span>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {appointmentStats.map((stat, index) => (
            <motion.div
              key={index}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 }}
              className="group relative"
            >
              <div className="bg-white rounded-xl p-6 border border-gray-200 hover:shadow-lg transition-all duration-300 h-full">
                {/* Icon Container */}
                <div className="mb-6">
                  <div className={`p-3 rounded-xl bg-${stat.color}-50 border border-${stat.color}-100 inline-block`}>
                    <div className={`text-${stat.color}-600`}>
                      {stat.icon}
                    </div>
                  </div>
                </div>
                
                {/* Stats Content */}
                <div className="space-y-2">
                  <h3 className="text-3xl font-bold text-gray-800">{stat.count}</h3>
                  <p className="font-medium text-gray-700">{stat.label}</p>
                  <p className="text-gray-500 text-sm">{stat.description}</p>
                </div>
                
                {/* Bottom Border */}
                <div className={`mt-6 h-1 w-full bg-${stat.color}-100 rounded-full overflow-hidden`}>
                  <div className={`h-full bg-${stat.color}-500 rounded-full transition-all duration-500 group-hover:w-full`} style={{ width: '75%' }} />
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      </div>

      {/* Earnings Statistics */}
      <div>
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
            <DollarSign className="w-6 h-6 text-emerald-600" />
            Earnings Summary
          </h2>
          <span className="text-sm text-gray-500 px-3 py-1 bg-gray-100 rounded-full">
            Updated daily
          </span>
        </div>
        
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {earningsStats.map((stat, index) => (
            <motion.div
              key={index}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 + 0.2 }}
              className="group relative"
            >
              <div className="bg-white rounded-xl p-6 border border-gray-200 hover:shadow-lg transition-all duration-300 h-full">
                {/* Icon Container */}
                <div className="mb-6">
                  <div className={`p-3 rounded-xl bg-${stat.color}-50 border border-${stat.color}-100 inline-block`}>
                    <div className={`text-${stat.color}-600`}>
                      {stat.icon}
                    </div>
                  </div>
                </div>
                
                {/* Stats Content */}
                <div className="space-y-2">
                  <h3 className="text-3xl font-bold text-gray-800">{stat.count}</h3>
                  <p className="font-medium text-gray-700">{stat.label}</p>
                  <p className="text-gray-500 text-sm">{stat.description}</p>
                </div>
                
                {/* Progress Bar */}
                <div className={`mt-6 h-1 w-full bg-${stat.color}-100 rounded-full overflow-hidden`}>
                  <div className={`h-full bg-${stat.color}-500 rounded-full transition-all duration-500 group-hover:w-full`} style={{ width: '85%' }} />
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      </div>

      {/* Quick Status Overview */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.5 }}
        className="grid grid-cols-1 md:grid-cols-2 gap-6"
      >
        {/* Next Appointment */}
        <div className="bg-white rounded-xl p-6 border border-gray-200">
          <div className="flex items-center gap-3 mb-4">
            <div className="p-2 bg-blue-50 rounded-lg">
              <Calendar className="w-6 h-6 text-blue-600" />
            </div>
            <h3 className="font-bold text-gray-800">Next Appointment</h3>
          </div>
          {stats?.nextAppointment ? (
            <>
              <p className="text-2xl font-bold text-gray-800 mb-2">
                {formatDateTime(stats.nextAppointment.date, stats.nextAppointment.startTime)}
              </p>
              <p className="text-gray-600 text-sm mb-1">
                Student: <span className="font-medium">{stats.nextAppointment.studentName}</span>
              </p>
              <p className="text-gray-600 text-sm mb-3">
                Amount: <span className="font-medium">${stats.nextAppointment.amount}</span>
              </p>
              <span className={`inline-block px-3 py-1 text-xs font-medium rounded-full ${
                stats.nextAppointment.status === 'confirmed' ? 'bg-emerald-100 text-emerald-700' :
                stats.nextAppointment.status === 'pending' ? 'bg-amber-100 text-amber-700' :
                'bg-gray-100 text-gray-700'
              }`}>
                {stats.nextAppointment.status.charAt(0).toUpperCase() + stats.nextAppointment.status.slice(1)}
              </span>
            </>
          ) : (
            <>
              <p className="text-2xl font-bold text-gray-800 mb-2">No upcoming appointments</p>
              <p className="text-gray-600 text-sm">Schedule your next session to get started</p>
            </>
          )}
        </div>
        
        {/* Next Payout */}
        <div className="bg-white rounded-xl p-6 border border-gray-200">
          <div className="flex items-center gap-3 mb-4">
            <div className="p-2 bg-emerald-50 rounded-lg">
              <Wallet className="w-6 h-6 text-emerald-600" />
            </div>
            <h3 className="font-bold text-gray-800">Next Payout</h3>
          </div>
          <p className="text-2xl font-bold text-gray-800 mb-2">
            ${(stats?.reservedEarnings || 0)}
          </p>
          <p className="text-gray-600 text-sm">Available reserved earnings</p>
          <p className="text-gray-500 text-xs mt-2">
            Processed on the 15th of each month
          </p>
        </div>
      </motion.div>
    </div>
  );
};

export default ForeignStudentDashboardHome;