'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { 
  MapPin, 
  GraduationCap, 
  DollarSign,
  Award, 
  CheckCircle,
  Calendar,
  Star,
  Clock,
  Users,
  Globe,
  MessageSquare,
  Phone,
  Mail,
  ChevronLeft,
  Share2,
  Bookmark,
  Shield,
  Zap,
  TrendingUp,
  Heart,
  BookOpen,
  Languages,
  Target,
  AlertTriangle,
  X
} from 'lucide-react';
import Image from 'next/image';
import BookingModal from '../../../components/organisms/BookingModal';
import Swal from 'sweetalert2';

const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000';

export default function DetailStudentPage({ 
  initialStudent, 
  initialAvailability, 
  slug 
}) {
  const router = useRouter();
  const [student, setStudent] = useState(initialStudent);
  const [availability, setAvailability] = useState(initialAvailability);
  const [isBookingModalOpen, setIsBookingModalOpen] = useState(false);
  const [isReportModalOpen, setIsReportModalOpen] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmittingReport, setIsSubmittingReport] = useState(false);
  
  // Report form state
  const [reportForm, setReportForm] = useState({
    name: '',
    email: '',
    phone: '',
    message: ''
  });

  const handleReportSubmit = async (e) => {
    e.preventDefault();
    
    if (!student) return;
    
    // Basic validation
    if (!reportForm.name.trim() || !reportForm.email.trim() || !reportForm.message.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Information',
        text: 'Please fill in all required fields (Name, Email, and Message).',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }
    
    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(reportForm.email)) {
      Swal.fire({
        icon: 'warning',
        title: 'Invalid Email',
        text: 'Please enter a valid email address.',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }
    
    setIsSubmittingReport(true);
    
    try {
      const response = await fetch(`${API_BASE_URL}/api/frontend/foreign-students/report`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          student_id: student.id,
          name: reportForm.name,
          email: reportForm.email,
          phone: reportForm.phone,
          message: reportForm.message
        })
      });
      
      const data = await response.json();
      
      if (data.success) {
        Swal.fire({
          icon: 'success',
          title: 'Report Submitted!',
          text: 'Thank you for your report. We will review it shortly.',
          confirmButtonColor: '#0B6D76'
        });
        
        // Reset form and close modal
        setReportForm({
          name: '',
          email: '',
          phone: '',
          message: ''
        });
        setIsReportModalOpen(false);
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Submission Failed',
          text: data.error || 'Failed to submit report. Please try again.',
          confirmButtonColor: '#0B6D76'
        });
      }
    } catch (error) {
      console.error('Error submitting report:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'An error occurred. Please try again later.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsSubmittingReport(false);
    }
  };

  const handleReportInputChange = (e) => {
    const { name, value } = e.target;
    setReportForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleBookAppointment = async () => {
    if (!student) return;

    try {
      const response = await fetch(
        `${API_BASE_URL}/api/frontend/userdashboard/foreign-student-availability/${student.id}`,
        {
          method: 'GET',
          credentials: 'include'
        }
      );

      if (!response.ok) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to check availability.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      const data = await response.json();
      
      if (!data.success || !data.schedule) {
        Swal.fire({
          icon: 'error',
          title: 'Not Available',
          text: 'This student has not set their availability yet.',
          confirmButtonColor: '#0B6D76'
        });
        return;
      }

      setIsBookingModalOpen(true);
    } catch (error) {
      console.error('Error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load availability. Please try again.',
        confirmButtonColor: '#0B6D76'
      });
    }
  };

  const handleBookingSuccess = () => {
    Swal.fire({
      icon: 'success',
      title: 'Success!',
      text: 'Appointment booked successfully.',
      confirmButtonColor: '#0B6D76'
    });
  };

  const getImageUrl = (imagePath) => {
    if (!imagePath) return '/assets/default-university.webp';
    
    if (imagePath.startsWith('http')) {
      return imagePath;
    }
    
    const cleanPath = imagePath.startsWith('/') ? imagePath.slice(1) : imagePath;
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${cleanPath}`;
  };

  const getDayName = (dayOfWeek) => {
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    return days[dayOfWeek] || `Day ${dayOfWeek}`;
  };

  const formatTime = (time) => {
    if (!time) return '';
    const [hours, minutes] = time.split(':');
    const hour = parseInt(hours);
    const period = hour >= 12 ? 'PM' : 'AM';
    const hour12 = hour % 12 || 12;
    return `${hour12}:${minutes} ${period}`;
  };

  const shareProfile = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: `${student?.name} - Foreign Student Guide`,
          text: `Connect with ${student?.name}, an international student guide on Universities Page`,
          url: window.location.href,
        });
      } catch (error) {
        console.log('Sharing cancelled:', error);
      }
    } else {
      await navigator.clipboard.writeText(window.location.href);
      Swal.fire({
        icon: 'success',
        title: 'Link Copied!',
        text: 'Profile link copied to clipboard',
        confirmButtonColor: '#0B6D76',
        timer: 2000
      });
    }
  };

  const refetchData = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/frontend/foreign-students/${slug}`);
      const data = await response.json();
      
      if (data.success) {
        setStudent(data.student);
        setAvailability(data.availability || []);
      }
    } catch (error) {
      console.error('Error refetching data:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to refresh profile data.',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (!student) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center max-w-md p-8 bg-white rounded-2xl shadow-lg">
          <div className="w-20 h-20 mx-auto bg-red-100 rounded-full flex items-center justify-center mb-4">
            <div className="text-red-500 text-2xl">⚠️</div>
          </div>
          <h3 className="text-xl font-bold text-gray-900 mb-2">Profile Not Found</h3>
          <p className="text-gray-600 mb-6">The student profile could not be loaded.</p>
          <button
            onClick={() => router.push('/students')}
            className="px-6 py-3 bg-teal-600 text-white rounded-xl font-medium hover:bg-teal-700 transition-colors"
          >
            Browse Other Students
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Navigation */}
      <div className="bg-white shadow-sm">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <button
              onClick={() => router.back()}
              className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition-colors"
              disabled={isLoading}
            >
              <ChevronLeft className="w-5 h-5" />
              Back to Students
            </button>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column - Profile Info */}
          <div className="lg:col-span-2 space-y-8">
            {/* Hero Section */}
            <div className="bg-white rounded-2xl shadow-lg p-8">
              <div className="flex flex-col md:flex-row md:items-start gap-6">
                {/* Profile Image */}
                <div className="flex-shrink-0">
                  <div className="relative">
                    <div className="w-32 h-32 rounded-2xl overflow-hidden border-4 border-white shadow-lg">
                      <Image
                        src={getImageUrl(student.profile_picture)}
                        alt={student.name}
                        width={128}
                        height={128}
                        className="w-full h-full object-cover"
                        priority
                      />
                    </div>
                    {student.is_active && (
                      <div className="absolute -bottom-2 -right-2 w-8 h-8 bg-green-500 rounded-full border-3 border-white flex items-center justify-center">
                        <CheckCircle className="w-4 h-4 text-white" />
                      </div>
                    )}
                  </div>
                </div>

                {/* Profile Info */}
                <div className="flex-1">
                  <div className="flex flex-col md:flex-row md:items-start md:justify-between mb-4">
                    <div>
                      <h1 className="text-3xl font-bold text-gray-900 mb-2">{student.name}</h1>
                      <div className="flex items-center gap-3 flex-wrap">
                        <div className="flex items-center gap-1 text-gray-600">
                          <MapPin className="w-4 h-4" />
                          <span>{student.country_name}</span>
                        </div>
                        <div className="flex items-center gap-1 text-amber-600">
                          <GraduationCap className="w-4 h-4" />
                          <span className="font-medium">{student.education_label}</span>
                        </div>
                      </div>
                    </div>

                    {/* Hour Rate Badge */}
                    <div className="mt-4 md:mt-0">
                      <div className="bg-gradient-to-r from-teal-500 to-teal-600 text-white px-6 py-3 rounded-xl shadow-lg">
                        <div className="text-sm opacity-90">Hourly Rate</div>
                        <div className="text-2xl font-bold">${student.hour_rate.toFixed(2)}</div>
                        <div className="text-xs opacity-90">per hour</div>
                      </div>
                    </div>
                  </div>

                  {/* Stats */}
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                    <div className="bg-gray-50 p-4 rounded-xl">
                      <div className="flex items-center gap-2 text-gray-600 mb-1">
                        <BookOpen className="w-4 h-4" />
                        <span className="text-sm">Education</span>
                      </div>
                      <div className="text-sm font-semibold text-gray-900">{student.education_label}</div>
                    </div>
                    <div className="bg-gray-50 p-4 rounded-xl">
                      <div className="flex items-center gap-2 text-gray-600 mb-1">
                        <Users className="w-4 h-4" />
                        <span className="text-sm">Status</span>
                      </div>
                      <div className="text-sm font-semibold text-teal-600">
                        {student.is_active ? 'Active' : 'Inactive'}
                      </div>
                    </div>
                    <div className="bg-gray-50 p-4 rounded-xl">
                      <div className="flex items-center gap-2 text-gray-600 mb-1">
                        <CheckCircle className="w-4 h-4" />
                        <span className="text-sm">Verified</span>
                      </div>
                      <div className="text-sm font-semibold text-green-600">
                        {student.is_verified ? 'Yes' : 'No'}
                      </div>
                    </div>
                    <div className="bg-gray-50 p-4 rounded-xl">
                      <div className="flex items-center gap-2 text-gray-600 mb-1">
                        <Globe className="w-4 h-4" />
                        <span className="text-sm">Timezone</span>
                      </div>
                      <div className="text-sm font-semibold text-gray-900">{student.timezone}</div>
                    </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="flex flex-wrap gap-4">
                    <button
                      onClick={handleBookAppointment}
                      disabled={!student.is_active || isLoading}
                      className="flex items-center cursor-pointer justify-center gap-3 px-6 py-3 bg-gradient-to-r from-teal-600 to-teal-700 hover:from-teal-700 hover:to-teal-800 text-white rounded-xl font-semibold transition-all shadow-lg hover:shadow-xl min-w-[200px] disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Calendar className="w-5 h-5" />
                      Book a Session
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* About Me Section */}
            {student.about_me && (
              <div className="bg-white rounded-2xl shadow-lg p-8">
                <h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                  <Heart className="w-6 h-6 text-teal-600" />
                  About Me
                </h2>
                <div className="prose max-w-none">
                  <p className="text-gray-700 whitespace-pre-line leading-relaxed">
                    {student.about_me}
                  </p>
                </div>
              </div>
            )}

            {/* Experience Section */}
            {student.experience && (
              <div className="bg-white rounded-2xl shadow-lg p-8">
                <h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                  <Target className="w-6 h-6 text-amber-600" />
                  Experience & Expertise
                </h2>
                <div className="prose max-w-none">
                  <p className="text-gray-700 whitespace-pre-line leading-relaxed">
                    {student.experience}
                  </p>
                </div>
              </div>
            )}

            {/* Availability Section */}
            {availability.length > 0 && (
              <div className="bg-white rounded-2xl shadow-lg p-8">
                <h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center gap-3">
                  <Clock className="w-6 h-6 text-blue-600" />
                  Availability Schedule
                </h2>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {availability.map((slot, index) => (
                    <div key={index} className="bg-blue-50 p-4 rounded-xl">
                      <h3 className="font-semibold text-blue-900 mb-2">
                        {getDayName(slot.day_of_week)}
                      </h3>
                      {slot.time_slots && slot.time_slots.length > 0 ? (
                        <div className="space-y-1">
                          {slot.time_slots.map((time, idx) => (
                            <div key={idx} className="text-sm text-blue-700">
                              {formatTime(time.start)} - {formatTime(time.end)}
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="text-sm text-blue-600">Available all day</p>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Right Column - Sidebar */}
          <div className="space-y-6">

            {/* Profile Stats */}
            <div className="bg-white rounded-2xl shadow-lg p-6">
              <h3 className="text-lg font-bold text-gray-900 mb-4">Profile Stats</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">Member Since</span>
                  <span className="font-medium text-gray-900">
                    {new Date(student.created_at).toLocaleDateString('en-US', {
                      year: 'numeric',
                      month: 'short'
                    })}
                  </span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">Gender</span>
                  <span className="font-medium text-gray-900 capitalize">{student.gender || 'Not specified'}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">Timezone</span>
                  <span className="font-medium text-gray-900">{student.timezone || 'Not set'}</span>
                </div>
              </div>
            </div>

            {/* Report Button */}
            <div className="bg-red-50 border border-red-200 rounded-2xl p-6">
              <h3 className="text-lg font-bold text-gray-900 mb-3">Need Help?</h3>
              <p className="text-gray-600 text-sm mb-4">
                If you encounter any issues or have concerns about this profile, please report it.
              </p>
              <button
                onClick={() => setIsReportModalOpen(true)}
                className="w-full px-4 py-2.5 bg-white border border-red-300 text-red-600 hover:bg-red-50 rounded-xl font-medium transition-colors flex items-center justify-center gap-2"
              >
                <AlertTriangle className="w-4 h-4" />
                Report Profile
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Report Modal */}
      {isReportModalOpen && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl w-full max-w-md overflow-hidden animate-fadeIn">
            {/* Modal Header */}
            <div className="bg-gradient-to-r from-red-500 to-red-600 p-6 text-white">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <AlertTriangle className="w-6 h-6" />
                  <h2 className="text-xl font-bold">Report Student Profile</h2>
                </div>
                <button
                  onClick={() => setIsReportModalOpen(false)}
                  className="text-white/80 hover:text-white transition-colors"
                  disabled={isSubmittingReport}
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              <p className="text-red-100 text-sm mt-2">
                Report: {student?.name}
              </p>
            </div>

            {/* Modal Body */}
            <div className="p-6">
              <form onSubmit={handleReportSubmit}>
                <div className="space-y-4">
                  {/* Name Field */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Your Name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      name="name"
                      value={reportForm.name}
                      onChange={handleReportInputChange}
                      className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-all duration-200"
                      placeholder="Enter your full name"
                      required
                      disabled={isSubmittingReport}
                    />
                  </div>

                  {/* Email Field */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Email Address <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="email"
                      name="email"
                      value={reportForm.email}
                      onChange={handleReportInputChange}
                      className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-all duration-200"
                      placeholder="Enter your email address"
                      required
                      disabled={isSubmittingReport}
                    />
                  </div>

                  {/* Phone Field */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Phone Number
                    </label>
                    <input
                      type="tel"
                      name="phone"
                      value={reportForm.phone}
                      onChange={handleReportInputChange}
                      className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-all duration-200"
                      placeholder="Enter your phone number"
                      disabled={isSubmittingReport}
                    />
                  </div>

                  {/* Message Field */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Report Details <span className="text-red-500">*</span>
                    </label>
                    <textarea
                      name="message"
                      value={reportForm.message}
                      onChange={handleReportInputChange}
                      rows={4}
                      className="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-all duration-200 resize-none"
                      placeholder="Please describe the issue or concern you have with this student profile..."
                      required
                      disabled={isSubmittingReport}
                    />
                    <p className="text-xs text-gray-500 mt-2">
                      Please provide specific details about your concern.
                    </p>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="flex gap-3 mt-6">
                  <button
                    type="button"
                    onClick={() => setIsReportModalOpen(false)}
                    className="flex-1 px-4 py-2.5 border border-gray-300 text-gray-700 hover:bg-gray-50 rounded-xl font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    disabled={isSubmittingReport}
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="flex-1 px-4 py-2.5 bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white rounded-xl font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
                    disabled={isSubmittingReport}
                  >
                    {isSubmittingReport ? (
                      <>
                        <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                        Submitting...
                      </>
                    ) : (
                      <>
                        <AlertTriangle className="w-4 h-4" />
                        Submit Report
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>

            {/* Modal Footer */}
            <div className="bg-gray-50 px-6 py-4 border-t border-gray-200">
              <p className="text-xs text-gray-500 text-center">
                Your report will be reviewed by our team. We take all reports seriously and will investigate promptly.
              </p>
            </div>
          </div>
        </div>
      )}

      {/* Booking Modal */}
      <BookingModal
        student={student}
        isOpen={isBookingModalOpen}
        onClose={() => setIsBookingModalOpen(false)}
        onBookingSuccess={handleBookingSuccess}
      />

      {/* Add animation styles */}
      <style jsx global>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(-10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.2s ease-out;
        }
      `}</style>
    </div>
  );
}