import { useState, useEffect, useRef } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
    Save, Upload,
    Home, ChevronRight, User, Instagram, Calendar, Briefcase
} from 'lucide-react';
import Toast from '../../../components/Toast';
import CustomDatePicker from '../../../components/admin/CustomDatePicker';
import AdminLayout from '../../../components/admin/AdminLayout';
import useToast from '../../../hooks/useToast';
import * as authApi from '../../../api/admin/auth';
import * as membersApi from '../../../api/admin/members';

function AdminMemberEdit() {
    const navigate = useNavigate();
    const { name } = useParams();
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const { toast, setToast } = useToast();
    const [imagePreview, setImagePreview] = useState(null);
    const [imageFile, setImageFile] = useState(null);
    
    const [formData, setFormData] = useState({
        name: '',
        birth_date: '',
        position: '',
        instagram: '',
        is_former: false
    });

    useEffect(() => {
        // 로그인 확인
        if (!authApi.hasToken()) {
            navigate('/admin');
            return;
        }

        setUser(authApi.getCurrentUser());
        fetchMember();
    }, [navigate, name]);

    const fetchMember = async () => {
        try {
            const data = await membersApi.getMember(encodeURIComponent(name));
            setFormData({
                name: data.name || '',
                birth_date: data.birth_date ? data.birth_date.split('T')[0] : '',
                position: data.position || '',
                instagram: data.instagram || '',
                is_former: !!data.is_former
            });
            setImagePreview(data.image_url);
            setLoading(false);
        } catch (error) {
            console.error('멤버 로드 오류:', error);
            setToast({ message: '멤버 정보를 불러올 수 없습니다.', type: 'error' });
            setLoading(false);
        }
    };

    const handleImageChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            setImageFile(file);
            const reader = new FileReader();
            reader.onloadend = () => setImagePreview(reader.result);
            reader.readAsDataURL(file);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true);

        try {
            const formDataToSend = new FormData();
            
            formDataToSend.append('name', formData.name);
            formDataToSend.append('birth_date', formData.birth_date);
            formDataToSend.append('position', formData.position);
            formDataToSend.append('instagram', formData.instagram);
            formDataToSend.append('is_former', formData.is_former);
            
            if (imageFile) {
                formDataToSend.append('image', imageFile);
            }

            await membersApi.updateMember(encodeURIComponent(name), formDataToSend);
            setToast({ message: '멤버 정보가 수정되었습니다.', type: 'success' });
            setTimeout(() => navigate('/admin/members'), 1000);
        } catch (error) {
            console.error('수정 오류:', error);
            setToast({ message: '수정 중 오류가 발생했습니다.', type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    return (
        <AdminLayout user={user}>
            {/* Toast */}
            <Toast toast={toast} onClose={() => setToast(null)} />

            {/* 메인 콘텐츠 */}
            <div className="max-w-4xl mx-auto px-6 py-8">
                {/* 브레드크럼 */}
                <div className="flex items-center gap-2 text-sm text-gray-400 mb-8">
                    <Link to="/admin/dashboard" className="hover:text-primary transition-colors">
                        <Home size={16} />
                    </Link>
                    <ChevronRight size={14} />
                    <Link to="/admin/members" className="hover:text-primary transition-colors">
                        멤버 관리
                    </Link>
                    <ChevronRight size={14} />
                    <span className="text-gray-700">멤버 수정</span>
                </div>

                {/* 타이틀 */}
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-2">멤버 수정</h1>
                    <p className="text-gray-500">멤버 정보를 수정합니다</p>
                </div>

                {loading ? (
                    <div className="flex justify-center items-center py-20">
                        <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
                    </div>
                ) : (
                    <motion.form
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        onSubmit={handleSubmit}
                        className="bg-white rounded-2xl p-8 border border-gray-100 shadow-sm"
                    >
                        <div className="grid grid-cols-3 gap-8">
                            {/* 이미지 업로드 영역 */}
                            <div className="col-span-1">
                                <label className="block text-sm font-medium text-gray-700 mb-3">
                                    프로필 사진
                                </label>
                                <div 
                                    className="aspect-[3/4] rounded-2xl border-2 border-dashed border-gray-200 overflow-hidden relative group cursor-pointer hover:border-primary transition-colors"
                                    onClick={() => document.getElementById('imageInput').click()}
                                >
                                    {imagePreview ? (
                                        <>
                                            <img 
                                                src={imagePreview} 
                                                alt="프로필 미리보기" 
                                                className="w-full h-full object-cover"
                                            />
                                            <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                <div className="text-white text-center">
                                                    <Upload size={32} className="mx-auto mb-2" />
                                                    <span className="text-sm">변경</span>
                                                </div>
                                            </div>
                                        </>
                                    ) : (
                                        <div className="w-full h-full flex flex-col items-center justify-center text-gray-400">
                                            <User size={48} className="mb-2" />
                                            <span className="text-sm">클릭하여 업로드</span>
                                        </div>
                                    )}
                                </div>
                                <input
                                    id="imageInput"
                                    type="file"
                                    accept="image/*"
                                    onChange={handleImageChange}
                                    className="hidden"
                                />
                            </div>

                            {/* 입력 폼 영역 */}
                            <div className="col-span-2 space-y-6">
                                {/* 이름 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        <User size={16} className="inline mr-1" />
                                        이름 *
                                    </label>
                                    <input
                                        type="text"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        required
                                        className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                                        placeholder="멤버 이름"
                                    />
                                </div>

                                {/* 생년월일 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        <Calendar size={16} className="inline mr-1" />
                                        생년월일
                                    </label>
                                    <CustomDatePicker
                                        value={formData.birth_date}
                                        onChange={(date) => setFormData({ ...formData, birth_date: date })}
                                    />
                                </div>

                                {/* 포지션 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        <Briefcase size={16} className="inline mr-1" />
                                        포지션
                                    </label>
                                    <input
                                        type="text"
                                        value={formData.position}
                                        onChange={(e) => setFormData({ ...formData, position: e.target.value })}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                                        placeholder="메인보컬, 리드댄서 등"
                                    />
                                </div>

                                {/* 인스타그램 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        <Instagram size={16} className="inline mr-1" />
                                        인스타그램
                                    </label>
                                    <input
                                        type="text"
                                        value={formData.instagram}
                                        onChange={(e) => setFormData({ ...formData, instagram: e.target.value })}
                                        className="w-full px-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                                        placeholder="@username"
                                    />
                                </div>

                                {/* 활동 상태 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        활동 상태
                                    </label>
                                    <div className="flex items-center gap-3">
                                        <button
                                            type="button"
                                            onClick={() => setFormData({ ...formData, is_former: false })}
                                            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                                                !formData.is_former 
                                                    ? 'bg-primary text-white' 
                                                    : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                                            }`}
                                        >
                                            활동 중
                                        </button>
                                        <button
                                            type="button"
                                            onClick={() => setFormData({ ...formData, is_former: true })}
                                            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                                                formData.is_former 
                                                    ? 'bg-gray-600 text-white' 
                                                    : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                                            }`}
                                        >
                                            탈퇴
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* 버튼 영역 */}
                        <div className="flex justify-end gap-3 mt-8 pt-6 border-t border-gray-100">
                            <button
                                type="button"
                                onClick={() => navigate('/admin/members')}
                                className="px-6 py-3 text-gray-600 hover:bg-gray-100 rounded-xl transition-colors"
                            >
                                취소
                            </button>
                            <button
                                type="submit"
                                disabled={saving}
                                className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors disabled:opacity-50"
                            >
                                {saving ? (
                                    <>
                                        <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                                        저장 중...
                                    </>
                                ) : (
                                    <>
                                        <Save size={18} />
                                        저장
                                    </>
                                )}
                            </button>
                        </div>
                    </motion.form>
                )}
            </div>
        </AdminLayout>
    );
}

export default AdminMemberEdit;
