'use client';

import { useState, useRef, useCallback } from 'react';
import Link from 'next/link';
import { useAuth } from '@/contexts/AuthContext';
import { auth } from '@/lib/firebase';

const FILE_NAME_REGEX = /^([가-힣a-zA-Z]+(?:_[가-힣a-zA-Z]+)*)_(.+)_(\d{4})\.pdf$/i;
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

interface FileItem {
    file: File;
    status: 'valid' | 'invalid';
    errorMsg?: string;
    uploadStatus?: 'uploading' | 'success' | 'error';
    uploadError?: string;
    driveFileId?: string;
    jobId?: string;
    parsedMeta?: { companyName: string; productName: string; effectiveDate: string; category: string };
    categoryOverride?: string;
}

function validateFile(name: string, size: number): { valid: boolean; errorMsg?: string } {
    if (!name.toLowerCase().endsWith('.pdf')) {
        return { valid: false, errorMsg: 'PDF 파일만 업로드 가능합니다' };
    }
    if (size > MAX_FILE_SIZE) {
        return { valid: false, errorMsg: `파일 크기 초과: ${(size / 1024 / 1024).toFixed(1)}MB (최대 50MB)` };
    }
    if (!FILE_NAME_REGEX.test(name)) {
        return { valid: false, errorMsg: '파일명 형식 오류: {회사명}_{상품명}_{YYMM}.pdf 로 맞춰주세요' };
    }
    const match = name.match(FILE_NAME_REGEX)!;
    const yymm = match[3];
    const month = parseInt(yymm.slice(2, 4), 10);
    if (month < 1 || month > 12) {
        return { valid: false, errorMsg: `월 표기 오류: ${yymm} (MM은 01~12)` };
    }
    return { valid: true };
}

function parseFileNamePreview(name: string): { companyName: string; productName: string; effectiveDate: string; category: string } | null {
    const match = name.match(FILE_NAME_REGEX);
    if (!match) return null;
    const [, companyName, productName, yymm] = match;
    const year = `20${yymm.slice(0, 2)}`;
    const month = yymm.slice(2, 4);
    const NON_LIFE = ['화재', '해상', '손보', '손해'];
    const VARIABLE = ['변액'];
    let category = '생명보험';
    if (VARIABLE.some(k => companyName.includes(k))) category = '변액보험';
    else if (NON_LIFE.some(k => companyName.includes(k))) category = '손해보험';
    return { companyName, productName, effectiveDate: `${year}-${month}`, category };
}

export default function AdminUploadPage() {
    const { user } = useAuth();
    const [files, setFiles] = useState<FileItem[]>([]);
    const [isDragging, setIsDragging] = useState(false);
    const [isUploading, setIsUploading] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);

    const addFiles = useCallback((newFiles: FileList | File[]) => {
        const arr = Array.from(newFiles);
        const items: FileItem[] = arr.map((f) => {
            const { valid, errorMsg } = validateFile(f.name, f.size);
            const parsedMeta = valid ? parseFileNamePreview(f.name) ?? undefined : undefined;
            return { file: f, status: valid ? 'valid' : 'invalid', errorMsg, parsedMeta };
        });
        setFiles((prev) => {
            const existingNames = new Set(prev.map(p => p.file.name));
            const deduplicated = items.filter(i => !existingNames.has(i.file.name));
            return [...prev, ...deduplicated];
        });
    }, []);

    const handleDrop = useCallback((e: React.DragEvent) => {
        e.preventDefault();
        setIsDragging(false);
        addFiles(e.dataTransfer.files);
    }, [addFiles]);

    const handleDragOver = (e: React.DragEvent) => {
        e.preventDefault();
        setIsDragging(true);
    };

    const handleDragLeave = () => setIsDragging(false);

    const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) addFiles(e.target.files);
        e.target.value = '';
    };

    const removeFile = (index: number) => {
        setFiles(prev => prev.filter((_, i) => i !== index));
    };

    const validFiles = files.filter(f => f.status === 'valid');
    const invalidFiles = files.filter(f => f.status === 'invalid');

    const handleUpload = async () => {
        if (!user || !validFiles.length) return;
        setIsUploading(true);

        // 업로드 대상만 uploading 상태로 변경
        setFiles(prev => prev.map(f =>
            f.status === 'valid' ? { ...f, uploadStatus: 'uploading' } : f
        ));

        try {
            const idToken = await auth.currentUser?.getIdToken();
            const formData = new FormData();
            validFiles.forEach(item => formData.append('files', item.file));

            // 카테고리 오버라이드 전송 (파일명 → 카테고리 매핑)
            const categoryOverrides: Record<string, string> = {};
            validFiles.forEach(item => {
                if (item.categoryOverride) {
                    categoryOverrides[item.file.name] = item.categoryOverride;
                }
            });
            if (Object.keys(categoryOverrides).length > 0) {
                formData.append('categories', JSON.stringify(categoryOverrides));
            }

            const res = await fetch('/api/admin/drive-upload', {
                method: 'POST',
                headers: { Authorization: `Bearer ${idToken}` },
                body: formData,
            });

            const data = await res.json();

            if (!res.ok) {
                setFiles(prev => prev.map(f =>
                    f.status === 'valid' ? { ...f, uploadStatus: 'error', uploadError: data.error } : f
                ));
                return;
            }

            // 결과 반영
            const resultMap = new Map<string, { success: boolean; driveFileId?: string; jobId?: string; error?: string }>(
                data.results.map((r: any) => [r.fileName, r])
            );

            setFiles(prev => prev.map(f => {
                if (f.status !== 'valid') return f;
                const result = resultMap.get(f.file.name);
                if (!result) return f;
                return {
                    ...f,
                    uploadStatus: result.success ? 'success' : 'error',
                    driveFileId: result.driveFileId,
                    jobId: result.jobId,
                    uploadError: result.error,
                };
            }));
        } catch (err: any) {
            setFiles(prev => prev.map(f =>
                f.status === 'valid' ? { ...f, uploadStatus: 'error', uploadError: err.message } : f
            ));
        } finally {
            setIsUploading(false);
        }
    };

    const clearCompleted = () => {
        setFiles(prev => prev.filter(f => f.uploadStatus !== 'success'));
    };

    return (
        <div className="p-6 md:p-8 max-w-4xl">
            <div className="mb-6">
                <h1 className="text-2xl font-bold text-gray-900">문서 업로드</h1>
                <p className="text-sm text-gray-500 mt-1">약관 PDF를 Google Drive에 자동으로 정리하여 업로드합니다.</p>
            </div>

            {/* 파일명 가이드 */}
            <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6">
                <div className="flex gap-3">
                    <svg className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div>
                        <p className="text-sm font-semibold text-amber-800 mb-1">파일명 네이밍 규칙 (필독)</p>
                        <code className="text-xs bg-amber-100 text-amber-900 px-2 py-0.5 rounded font-mono">
                            {'{회사명}_{상품명}_{YYMM}.pdf'}
                        </code>
                        <p className="text-xs text-amber-700 mt-1.5">
                            예시: <code className="bg-amber-100 px-1 rounded">삼성생명_퍼펙트종신_2403.pdf</code>,{' '}
                            <code className="bg-amber-100 px-1 rounded">현대해상_운전자보험_2501.pdf</code>
                        </p>
                        <p className="text-xs text-amber-600 mt-1">
                            YYMM: 연도 2자리 + 월 2자리 (예: 2403 = 2024년 3월)
                        </p>
                    </div>
                </div>
            </div>

            {/* 드롭존 */}
            <div
                onDrop={handleDrop}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onClick={() => fileInputRef.current?.click()}
                className={`border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-colors mb-6 ${
                    isDragging
                        ? 'border-indigo-400 bg-indigo-50'
                        : 'border-gray-300 bg-gray-50 hover:border-indigo-300 hover:bg-indigo-50/30'
                }`}
            >
                <svg className="w-10 h-10 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
                <p className="text-sm font-medium text-gray-700">PDF 파일을 여기에 드래그하거나 클릭하여 선택</p>
                <p className="text-xs text-gray-400 mt-1">여러 파일 동시 선택 가능</p>
                <input
                    ref={fileInputRef}
                    type="file"
                    accept=".pdf"
                    multiple
                    onChange={handleFileInput}
                    className="hidden"
                />
            </div>

            {/* 파일 목록 */}
            {files.length > 0 && (
                <div className="space-y-3 mb-6">
                    {/* 통과 파일 */}
                    {validFiles.length > 0 && (
                        <div>
                            <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                통과 ({validFiles.length}개)
                            </p>
                            <div className="space-y-2">
                                {files.map((item, index) => {
                                    if (item.status !== 'valid') return null;
                                    return (
                                        <div key={index} className="flex items-center gap-3 bg-white rounded-lg border border-gray-200 px-4 py-3">
                                            {/* 상태 아이콘 */}
                                            <div className="flex-shrink-0">
                                                {!item.uploadStatus && (
                                                    <div className="w-5 h-5 rounded-full bg-green-100 flex items-center justify-center">
                                                        <svg className="w-3 h-3 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
                                                        </svg>
                                                    </div>
                                                )}
                                                {item.uploadStatus === 'uploading' && (
                                                    <div className="w-5 h-5 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin" />
                                                )}
                                                {item.uploadStatus === 'success' && (
                                                    <div className="w-5 h-5 rounded-full bg-indigo-100 flex items-center justify-center">
                                                        <svg className="w-3 h-3 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
                                                        </svg>
                                                    </div>
                                                )}
                                                {item.uploadStatus === 'error' && (
                                                    <div className="w-5 h-5 rounded-full bg-red-100 flex items-center justify-center">
                                                        <svg className="w-3 h-3 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M6 18L18 6M6 6l12 12" />
                                                        </svg>
                                                    </div>
                                                )}
                                            </div>

                                            {/* 파일명 */}
                                            <div className="flex-1 min-w-0">
                                                <p className="text-sm font-medium text-gray-800 truncate">{item.file.name}</p>
                                                {item.uploadStatus === 'success' && (
                                                    <p className="text-xs text-indigo-600 mt-0.5">
                                                        Drive 업로드 완료
                                                        {item.jobId && (
                                                            <> · <Link href="/admin/terms" className="underline">인덱싱 상태 확인</Link></>
                                                        )}
                                                    </p>
                                                )}
                                                {item.uploadStatus === 'error' && (
                                                    <p className="text-xs text-red-500 mt-0.5">{item.uploadError}</p>
                                                )}
                                                {item.parsedMeta && !item.uploadStatus && (
                                                    <div className="flex gap-2 mt-1 flex-wrap items-center">
                                                        <span className="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded">{item.parsedMeta.companyName}</span>
                                                        <span className="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded">{item.parsedMeta.productName}</span>
                                                        <span className="text-xs bg-slate-100 text-slate-600 px-1.5 py-0.5 rounded">{item.parsedMeta.effectiveDate}</span>
                                                        {item.categoryOverride ? (
                                                            <select
                                                                value={item.categoryOverride}
                                                                onChange={e => {
                                                                    const val = e.target.value;
                                                                    setFiles(prev => prev.map((fi, i) => i === index ? { ...fi, categoryOverride: val } : fi));
                                                                }}
                                                                className="text-xs border border-indigo-300 rounded px-1 py-0.5 bg-white text-indigo-700 cursor-pointer"
                                                            >
                                                                <option value="생명보험">생명보험</option>
                                                                <option value="손해보험">손해보험</option>
                                                                <option value="변액보험">변액보험</option>
                                                            </select>
                                                        ) : (
                                                            <span
                                                                className={`text-xs px-1.5 py-0.5 rounded cursor-pointer hover:opacity-75 transition-opacity ${
                                                                    item.parsedMeta.category === '손해보험' ? 'bg-purple-100 text-purple-700' :
                                                                    item.parsedMeta.category === '변액보험' ? 'bg-amber-100 text-amber-700' :
                                                                    'bg-blue-100 text-blue-700'
                                                                }`}
                                                                onClick={() => setFiles(prev => prev.map((fi, i) => i === index ? { ...fi, categoryOverride: fi.parsedMeta?.category ?? '생명보험' } : fi))}
                                                                title="클릭하여 카테고리 변경"
                                                            >
                                                                {item.parsedMeta.category} ✎
                                                            </span>
                                                        )}
                                                    </div>
                                                )}
                                            </div>

                                            {/* 파일 크기 */}
                                            <span className="text-xs text-gray-400 flex-shrink-0">
                                                {(item.file.size / 1024 / 1024).toFixed(1)} MB
                                            </span>

                                            {/* 삭제 버튼 */}
                                            {!item.uploadStatus && (
                                                <button
                                                    onClick={() => removeFile(index)}
                                                    className="flex-shrink-0 text-gray-300 hover:text-gray-500 transition-colors"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                                    </svg>
                                                </button>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    )}

                    {/* 실패 파일 */}
                    {invalidFiles.length > 0 && (
                        <div>
                            <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                규칙 위반 ({invalidFiles.length}개) — 업로드 불가
                            </p>
                            <div className="space-y-2">
                                {files.map((item, index) => {
                                    if (item.status !== 'invalid') return null;
                                    return (
                                        <div key={index} className="flex items-center gap-3 bg-red-50 rounded-lg border border-red-200 px-4 py-3">
                                            <div className="w-5 h-5 rounded-full bg-red-100 flex items-center justify-center flex-shrink-0">
                                                <svg className="w-3 h-3 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M6 18L18 6M6 6l12 12" />
                                                </svg>
                                            </div>
                                            <div className="flex-1 min-w-0">
                                                <p className="text-sm font-medium text-red-800 truncate">{item.file.name}</p>
                                                <p className="text-xs text-red-500 mt-0.5">{item.errorMsg}</p>
                                            </div>
                                            <button
                                                onClick={() => removeFile(index)}
                                                className="flex-shrink-0 text-red-300 hover:text-red-500 transition-colors"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                                </svg>
                                            </button>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    )}
                </div>
            )}

            {/* 액션 버튼 */}
            <div className="flex items-center gap-3">
                {validFiles.some(f => f.uploadStatus === 'success') && (
                    <button
                        onClick={clearCompleted}
                        className="px-4 py-2 text-sm text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                    >
                        완료 항목 지우기
                    </button>
                )}
                <button
                    onClick={handleUpload}
                    disabled={
                        isUploading ||
                        validFiles.filter(f => !f.uploadStatus).length === 0
                    }
                    className="px-6 py-2.5 bg-indigo-600 text-white text-sm font-semibold rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center gap-2"
                >
                    {isUploading ? (
                        <>
                            <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                            업로드 중...
                        </>
                    ) : (
                        <>
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                            </svg>
                            Google Drive에 {validFiles.filter(f => !f.uploadStatus).length}개 업로드
                        </>
                    )}
                </button>
            </div>
        </div>
    );
}
