import { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Save, Upload, X, Home, ChevronRight, User, Instagram, Calendar, Tag } from 'lucide-react';
import Toast from '../../../components/Toast';
import CustomDatePicker from '../../../components/admin/CustomDatePicker';
import AdminLayout from '../../../components/admin/AdminLayout';
import useAdminAuth from '../../../hooks/useAdminAuth';
import useToast from '../../../hooks/useToast';
import { fetchAdminApi, fetchAdminFormData } from '../../../api';

function AdminMemberEdit() {
    const navigate = useNavigate();
    const queryClient = useQueryClient();
    const { name } = useParams();
    const { user, isAuthenticated } = useAdminAuth();
    const { toast, setToast } = useToast();

    const [saving, setSaving] = useState(false);
    const [imagePreview, setImagePreview] = useState(null);
    const [imageFile, setImageFile] = useState(null);
    const [nicknameInput, setNicknameInput] = useState('');
    const [formData, setFormData] = useState({
        name: '',
        name_en: '',
        birth_date: '',
        instagram: '',
        is_former: false,
        nicknames: []
    });

    // 멤버 상세 조회
    const { data: memberData, isLoading: loading, isError } = useQuery({
        queryKey: ['admin', 'member', name],
        queryFn: () => fetchAdminApi(`/api/members/${encodeURIComponent(name)}`),
        enabled: isAuthenticated,
    });

    // 데이터 로드 시 폼에 반영
    useEffect(() => {
        if (memberData) {
            const birthDate = memberData.birth_date
                ? memberData.birth_date.split('T')[0]
                : '';
            setFormData({
                name: memberData.name || '',
                name_en: memberData.name_en || '',
                birth_date: birthDate,
                instagram: memberData.instagram || '',
                is_former: !!memberData.is_former,
                nicknames: memberData.nicknames || []
            });
            setImagePreview(memberData.image_url);
        }
    }, [memberData]);

    // 에러 처리
    useEffect(() => {
        if (isError) {
            setToast({ message: '멤버 정보를 불러오는데 실패했습니다.', type: 'error' });
        }
    }, [isError, setToast]);

    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 handleAddNickname = () => {
        const trimmed = nicknameInput.trim();
        if (trimmed && !formData.nicknames.includes(trimmed)) {
            setFormData({
                ...formData,
                nicknames: [...formData.nicknames, trimmed]
            });
            setNicknameInput('');
        }
    };

    // 별명 삭제
    const handleRemoveNickname = (nickname) => {
        setFormData({
            ...formData,
            nicknames: formData.nicknames.filter(n => n !== nickname)
        });
    };

    // Enter 키로 별명 추가
    const handleNicknameKeyDown = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            handleAddNickname();
        }
    };

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

        try {
            const form = new FormData();
            form.append('name', formData.name);
            form.append('name_en', formData.name_en);
            form.append('birth_date', formData.birth_date);
            form.append('instagram', formData.instagram);
            form.append('is_former', formData.is_former ? '1' : '0');
            form.append('nicknames', JSON.stringify(formData.nicknames));

            if (imageFile) {
                form.append('image', imageFile);
            }

            await fetchAdminFormData(`/api/members/${encodeURIComponent(name)}`, form, 'PUT');

            // 목록 캐시 무효화 (목록 페이지에서 최신 데이터 표시)
            queryClient.invalidateQueries({ queryKey: ['admin', 'members'] });

            // 목록 페이지로 이동하면서 토스트 메시지 전달
            navigate('/admin/members', {
                state: { toast: { message: '멤버 정보가 수정되었습니다.', type: 'success' } }
            });
        } catch (err) {
            setToast({ message: err.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 className="grid grid-cols-2 gap-4">
                                    <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">
                                            영문 이름
                                        </label>
                                        <input
                                            type="text"
                                            value={formData.name_en}
                                            onChange={(e) => setFormData({ ...formData, name_en: 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="ENGLISH NAME"
                                        />
                                    </div>
                                </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">
                                        <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="https://www.instagram.com/username"
                                    />
                                </div>

                                {/* 별명 */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">
                                        <Tag size={16} className="inline mr-1" />
                                        별명
                                    </label>
                                    <div className="space-y-3">
                                        {/* 별명 입력 */}
                                        <input
                                            type="text"
                                            value={nicknameInput}
                                            onChange={(e) => setNicknameInput(e.target.value)}
                                            onKeyDown={handleNicknameKeyDown}
                                            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="별명을 입력하고 Enter"
                                        />

                                        {/* 별명 태그 목록 */}
                                        {formData.nicknames.length > 0 && (
                                            <div className="flex flex-wrap gap-2">
                                                {formData.nicknames.map((nickname, index) => (
                                                    <span
                                                        key={index}
                                                        className="inline-flex items-center gap-1 px-3 py-1.5 bg-primary/10 text-primary rounded-full text-sm"
                                                    >
                                                        {nickname}
                                                        <button
                                                            type="button"
                                                            onClick={() => handleRemoveNickname(nickname)}
                                                            className="hover:bg-primary/20 rounded-full p-0.5 transition-colors"
                                                        >
                                                            <X size={14} />
                                                        </button>
                                                    </span>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                    <p className="mt-2 text-xs text-gray-400">
                                        별명은 일정 검색 시 사용됩니다
                                    </p>
                                </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;
