import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Instagram, Calendar } from 'lucide-react';

function Members() {
    const [members, setMembers] = useState([]);
    const [stats, setStats] = useState({ memberCount: 0, albumCount: 0, debutYear: 2018, fandomName: 'flover' });
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        Promise.all([
            fetch('/api/members').then(res => res.json()),
            fetch('/api/stats').then(res => res.json())
        ])
            .then(([membersData, statsData]) => {
                setMembers(membersData);
                setStats(statsData);
                setLoading(false);
            })
            .catch(error => {
                console.error('데이터 로드 오류:', error);
                setLoading(false);
            });
    }, []);

    // 날짜 포맷팅 함수
    const formatDate = (dateStr) => {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
    };

    if (loading) {
        return (
            <div className="py-16 flex justify-center items-center min-h-[60vh]">
                <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
            </div>
        );
    }

    return (
        <div className="py-16">
            <div className="max-w-7xl mx-auto px-6">
                {/* 헤더 */}
                <div className="text-center mb-12">
                    <motion.h1
                        initial={{ opacity: 0, y: -20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="text-4xl font-bold mb-4"
                    >
                        멤버
                    </motion.h1>
                    <motion.p
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        transition={{ delay: 0.2 }}
                        className="text-gray-500"
                    >
                        프로미스나인의 {stats.memberCount}명의 멤버를 소개합니다
                    </motion.p>
                </div>

                {/* 현재 멤버 그리드 */}
                <div className="grid grid-cols-5 gap-8">
                    {members.filter(m => !m.is_former).map((member, index) => (
                        <motion.div
                            key={member.id}
                            initial={{ opacity: 0, y: 30 }}
                            animate={{ opacity: 1, y: 0 }}
                            transition={{ delay: index * 0.1 }}
                            className="group h-full"
                        >
                            <div className="relative bg-white rounded-3xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 h-full flex flex-col">
                                {/* 이미지 */}
                                <div className="aspect-[3/4] bg-gray-100 overflow-hidden flex-shrink-0">
                                    <img
                                        src={member.image_url}
                                        alt={member.name}
                                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                                    />
                                </div>

                                {/* 정보 */}
                                <div className="p-6 flex-1 flex flex-col">
                                    <h3 className="text-xl font-bold mb-1">{member.name}</h3>
                                    <p className="text-primary text-sm font-medium mb-3 min-h-[20px]">{member.position || '\u00A0'}</p>
                                    
                                    <div className="flex items-center gap-2 text-sm text-gray-500 mb-4">
                                        <Calendar size={14} />
                                        <span>{formatDate(member.birth_date)}</span>
                                    </div>

                                    {/* 인스타그램 링크 */}
                                    {member.instagram && (
                                        <a
                                            href={member.instagram}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="inline-flex items-center gap-2 text-sm text-gray-500 hover:text-pink-500 transition-colors mt-auto"
                                        >
                                            <Instagram size={16} />
                                            <span>Instagram</span>
                                        </a>
                                    )}
                                </div>

                                {/* 호버 효과 - 컬러 바 */}
                                <div className="absolute bottom-0 left-0 right-0 h-1 bg-primary transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300" />
                            </div>
                        </motion.div>
                    ))}
                </div>

                {/* 탈퇴 멤버 섹션 - 콤팩트한 가로 리스트 */}
                {members.filter(m => m.is_former).length > 0 && (
                    <motion.div
                        initial={{ opacity: 0, y: 30 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.5 }}
                        className="mt-12"
                    >
                        <h2 className="text-lg font-bold mb-4 text-gray-400">전 멤버</h2>
                        <div className="flex gap-4">
                            {members.filter(m => m.is_former).map((member, index) => (
                                <motion.div
                                    key={member.id}
                                    initial={{ opacity: 0, x: -10 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    transition={{ delay: 0.6 + index * 0.05 }}
                                    className="group flex items-center gap-3 bg-gray-50 rounded-full pr-4 hover:bg-gray-100 transition-colors"
                                >
                                    {/* 작은 원형 이미지 */}
                                    <div className="w-12 h-12 rounded-full bg-gray-200 overflow-hidden flex-shrink-0">
                                        <img
                                            src={member.image_url || '/placeholder-member.jpg'}
                                            alt={member.name}
                                            className="w-full h-full object-cover grayscale group-hover:grayscale-0 transition-all duration-300"
                                        />
                                    </div>
                                    {/* 이름과 포지션 */}
                                    <div>
                                        <p className="font-medium text-gray-600 text-sm">{member.name}</p>
                                        <p className="text-xs text-gray-400">{member.position || ''}</p>
                                    </div>
                                </motion.div>
                            ))}
                        </div>
                    </motion.div>
                )}

                {/* 그룹 정보 */}
                <motion.div
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.6 }}
                    className="mt-16 bg-gradient-to-r from-primary to-primary-dark rounded-3xl p-10 text-white"
                >
                    <div className="grid grid-cols-4 gap-8 text-center">
                        <div>
                            <p className="text-4xl font-bold mb-2">2018.01.24</p>
                            <p className="text-white/70">데뷔일</p>
                        </div>
                        <div>
                            <p className="text-4xl font-bold mb-2">D+{(Math.floor((new Date() - new Date('2018-01-24')) / (1000 * 60 * 60 * 24)) + 1).toLocaleString()}</p>
                            <p className="text-white/70">D+Day</p>
                        </div>
                        <div>
                            <p className="text-4xl font-bold mb-2">{members.filter(m => !m.is_former).length}</p>
                            <p className="text-white/70">멤버 수</p>
                        </div>
                        <div>
                            <p className="text-4xl font-bold mb-2">{stats.fandomName}</p>
                            <p className="text-white/70">팬덤명</p>
                        </div>
                    </div>
                </motion.div>
            </div>
        </div>
    );
}

export default Members;
