'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { 
  BookOpen, 
  GraduationCap, 
  Globe, 
  Award, 
  Users, 
  Shield, 
  Sparkles, 
  MapPin,
  CheckCircle,
  Star,
  Target,
  Zap,
  MessageSquare,
  Phone,
  Mail
} from 'lucide-react';

// Import Shared Components
import ModernCard from '../../../app/components/shared/ModernCard';
import StatCard from '../../../app/components/shared/StatCard';
import FeatureCard from '../../../app/components/shared/FeatureCard';

interface TeamMember {
  user_first_name: string;
  user_last_name: string;
  user_profile_image: string;
  location: string;
}

interface TeamData {
  salesTeam: TeamMember[];
  itTeam: TeamMember[];
}

interface ApiResponse {
  success: boolean;
  data: TeamData;
  message?: string;
}

export default function OurTeam() {
  const [teamData, setTeamData] = useState<TeamData | null>(null);
  const [location, setLocation] = useState("lahore");
  const [loading, setLoading] = useState(false);
  const [locations, setLocations] = useState<string[]>([]);

  const fetchTeamData = async (selectedLocation: string = "lahore") => {
    setLoading(true);
    try {
      const res = await fetch(`/api/frontend/employees_crm?location=${selectedLocation}`);
      const data: ApiResponse = await res.json();
      
      if (data.success && data.data) {
        setTeamData(data.data);
        
        // Extract unique locations from the data
        const allMembers = [
          ...data.data.salesTeam,
          ...(data.data.itTeam || [])
        ];
        
        const uniqueLocations = Array.from(
          new Set(allMembers.map(member => member.location.toLowerCase()))
        );
        setLocations(uniqueLocations);
      } else {
        console.error('Failed to fetch team data:', data.message);
      }
    } catch (error) {
      console.error('Error fetching team data:', error);
    }
    setLoading(false);
  };

  useEffect(() => {
    // Load Lahore data by default
    fetchTeamData("lahore");
  }, []);

  // Get all members from both teams
  const getAllMembers = () => {
    if (!teamData) return [];
    
    const allMembers = [
      ...teamData.salesTeam.map(member => ({ ...member, team: 'Education Consultant' })),
    ];
    
    // Filter by selected location if not "all"
    if (location !== "all") {
      return allMembers.filter(member => 
        member.location.toLowerCase() === location.toLowerCase()
      );
    }
    
    return allMembers;
  };

  const allMembers = getAllMembers();

  // Handle location change
  const handleLocationChange = (newLocation: string) => {
    setLocation(newLocation);
    if (newLocation !== "all") {
      fetchTeamData(newLocation);
    } else {
      // For "all", we need to fetch all data
      fetchTeamData("all");
    }
  };

  // Function to get full image URL with S3 base URL
  const getImageUrl = (imagePath: string) => {
    // Construct URL with S3 base
    return `https://unipage-storage.s3.eu-north-1.amazonaws.com/${imagePath}`;
  };

  const stats = [
    { number: '10,000+', label: 'Students Guided', icon: Users, color: 'teal' },
    { number: '98%', label: 'Success Rate', icon: Award, color: 'blue' },
    { number: '25+', label: 'Countries Covered', icon: Globe, color: 'emerald' },
    { number: '50+', label: 'University Partners', icon: GraduationCap, color: 'amber' },
  ];

  const features = [
    {
      Icon: Users,
      title: "Expert Guidance",
      description: "Our consultants have firsthand experience with international education systems",
      color: "teal"
    },
    {
      Icon: BookOpen,
      title: "Personalized Approach",
      description: "We tailor our advice to your unique goals, background, and preferences",
      color: "blue"
    },
    {
      Icon: Globe,
      title: "Global Network",
      description: "Direct connections with universities worldwide for better opportunities",
      color: "emerald"
    },
    {
      Icon: Award,
      title: "Proven Success",
      description: "Track record of helping students gain admission to top institutions",
      color: "amber"
    }
  ];

  return (
    <div className="min-h-screen bg-linear-to-b from-gray-50 to-white">
      {/* Hero Section */}   
      <div className="relative">
        <div className="absolute inset-0 bg-linear-to-r from-teal-50/50 to-blue-50/50"></div>
        
        <div className="absolute top-0 left-0 w-full h-full overflow-hidden">
          {[...Array(20)].map((_, i) => (
            <div
              key={i}
              className="absolute rounded-full bg-linear-to-r from-teal-200/20 to-blue-200/20 animate-float"
              style={{
                width: Math.random() * 100 + 50,
                height: Math.random() * 100 + 50,
                top: `${Math.random() * 100}%`,
                left: `${Math.random() * 100}%`,
                animationDelay: `${Math.random() * 5}s`,
                animationDuration: `${Math.random() * 10 + 10}s`
              }}
            />
          ))}
        </div>

        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 md:py-28">
          <div className="text-center">
            <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-100 to-blue-100 text-teal-700 px-6 py-3 rounded-full text-sm font-semibold mb-8 animate-pulse">
              <Shield className="w-5 h-5" />
              Meet Our Expert Team
            </div>

            <h1 className="text-5xl md:text-7xl font-bold text-gray-900 mb-8 leading-tight">
              Meet{' '}
              <span className="bg-linear-to-r from-teal-600 to-blue-500 bg-clip-text text-transparent">
                Our Team
              </span>
            </h1>

            <p className="text-xl md:text-2xl text-gray-600 mb-12 max-w-3xl mx-auto leading-relaxed">
              Dedicated education experts committed to your study abroad success, 
              with years of experience and proven track records.
            </p>
          </div>
        </div>
      </div>

      {/* Stats Section */}
      <div className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Our Impact in Numbers
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Years of expertise translated into tangible results for thousands of students
            </p>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            {stats.map((stat, index) => (
              <StatCard 
                key={index}
                Icon={stat.icon}
                number={stat.number}
                label={stat.label}
                color={stat.color}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Team Grid */}
      <div className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Heading */}
          <div className="text-center mb-12">
            <h2 className="text-4xl font-bold text-gray-900 mb-4">Our Dedicated Team</h2>
            <p className="text-lg text-gray-600 max-w-3xl mx-auto">
              Meet our experienced education consultants working together to help you achieve your study abroad dreams
            </p>
          </div>

          {/* Enhanced Location Filter */}
          <div className="mb-12">
            <div className="text-center mb-6">
              <div className="inline-flex items-center gap-2 bg-linear-to-r from-teal-50 to-blue-50 text-teal-700 px-4 py-2 rounded-full text-sm font-semibold">
                <MapPin className="w-4 h-4" />
                Filter by Location
              </div>
            </div>
            
            <div className="flex flex-wrap justify-center gap-3 mb-8">
              <button
                onClick={() => handleLocationChange("all")}
                className={`px-6 py-3 rounded-xl font-medium transition-all duration-300 transform hover:scale-105 ${
                  location === "all" 
                    ? "bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg" 
                    : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                }`}
              >
                All Locations
              </button>
              
              {locations.map((city) => (
                <button
                  key={city}
                  onClick={() => handleLocationChange(city)}
                  className={`px-6 py-3 rounded-xl font-medium transition-all duration-300 transform hover:scale-105 capitalize ${
                    location === city 
                      ? "bg-linear-to-r from-teal-600 to-blue-500 text-white shadow-lg" 
                      : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                  }`}
                >
                  {city}
                </button>
              ))}
            </div>
            
            <div className="text-center">
              <p className="text-gray-500 text-sm">
                Showing {allMembers.length} team members from {location === "all" ? "all locations" : location}
              </p>
            </div>
          </div>

          {loading ? (
            <div className="text-center py-16">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-xl bg-linear-to-r from-teal-50 to-blue-50 mb-4">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div>
              </div>
              <p className="text-gray-600">Loading team members from {location}...</p>
            </div>
          ) : (
            <>
              {/* Employees Grid */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-8">
                {allMembers.map((member, index) => (
                  <ModernCard 
                    key={`${member.user_first_name}-${member.user_last_name}-${index}`} 
                    className="group hover:shadow-xl transition-all duration-300 transform hover:-translate-y-2 overflow-hidden"
                  >
                    <div className="relative h-72 overflow-hidden">
                      <Image
                        src={getImageUrl(member.user_profile_image) || "/default-avatar.png"}
                        alt={`${member.user_first_name} ${member.user_last_name}`}
                        fill
                        className="object-cover group-hover:scale-105 transition-transform duration-300"
                      />
                      <div className="absolute inset-0 bg-linear-to-t from-black/50 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                      
                      {/* Location Badge */}
                      <div className="absolute top-4 right-4">
                        <div className="bg-linear-to-r from-teal-600 to-blue-500 text-white px-3 py-1 rounded-full text-xs font-medium capitalize">
                          {member.location}
                        </div>
                      </div>
                    </div>
                    
                    <div className="p-6">
                      <div className="flex items-start justify-between">
                        <div>
                          <h3 className="text-xl font-bold text-gray-900 mb-1">
                            <span className="capitalize">
                              {member.user_first_name} {member.user_last_name}
                            </span>
                          </h3>
                          <p className="text-teal-600 font-semibold mb-2">
                            Education Consultant
                          </p>
                        </div>
                      </div>
                      
                      <div className="mt-4 pt-4 border-t border-gray-100">
                        <div className="flex items-center text-sm text-gray-600">
                          <MapPin className="w-4 h-4 mr-2 text-teal-600" />
                          <span className="capitalize">{member.location} Office</span>
                        </div>
                      </div>
                    </div>
                  </ModernCard>
                ))}
              </div>

              {allMembers.length === 0 && !loading && (
                <ModernCard className="text-center py-12">
                  <div className="w-16 h-16 bg-linear-to-r from-teal-50 to-blue-50 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Users className="w-8 h-8 text-teal-600" />
                  </div>
                  <p className="text-gray-500 text-lg mb-2">No team members found</p>
                  <p className="text-gray-400 text-sm">
                    Try selecting a different location or check back later.
                  </p>
                </ModernCard>
              )}
            </>
          )}
        </div>
      </div>

      {/* Features Section */}
      <div className="py-20 bg-linear-to-br from-gray-50 to-blue-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="text-center mb-12">
            <h2 className="text-3xl font-bold text-gray-900 mb-4">
              Why Choose Our Team?
            </h2>
            <p className="text-gray-600 max-w-2xl mx-auto">
              Our expertise and approach make us the ideal partner for your study abroad journey
            </p>
          </div>
          
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8">
            {features.map((feature, index) => (
              <FeatureCard
                key={index}
                Icon={feature.Icon}
                title={feature.title}
                description={feature.description}
                color={feature.color}
              />
            ))}
          </div>
        </div>
      </div>

      {/* CTA Section */}
      <div className="py-20">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <ModernCard className="p-12 text-center bg-linear-to-r from-teal-600 to-blue-500 text-white overflow-hidden">
            <div className="absolute top-0 left-0 right-0 h-1 bg-white/20"></div>
            
            <div className="relative z-10">
              <div className="inline-flex items-center gap-2 bg-white/20 backdrop-blur-sm text-white px-6 py-3 rounded-full text-sm font-semibold mb-6">
                <Sparkles className="w-5 h-5" />
                Ready to Start Your Journey?
              </div>

              <h2 className="text-4xl font-bold mb-6">
                Book Your Free Consultation Today
              </h2>

              <p className="text-xl text-white/80 mb-10 max-w-2xl mx-auto">
                Schedule a free consultation with one of our education experts to discuss your study abroad options
              </p>

              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Link
                  href="/free-consultation"
                  className="bg-white text-teal-600 font-semibold px-8 py-4 rounded-xl hover:shadow-xl transition-all duration-300 transform hover:scale-105"
                >
                  Book Consultation
                </Link>
                <Link
                  href="/contact-us"
                  className="border-2 border-white text-white font-semibold px-8 py-4 rounded-xl hover:bg-white/10 transition-all duration-300 backdrop-blur-sm"
                >
                  Contact Our Team
                </Link>
              </div>
            </div>
          </ModernCard>
        </div>
      </div>
    </div>
  );
}