import { useState, useEffect, useCallback } from 'react';
import {
    bypassApi,
    type BypassConfigRequest,
    type BypassConfigResponse,
    type CodeGenerationResult,
    type WebClientBeanInfo,
} from '../api/bypassApi';
import { useToastContext } from '../contexts/ToastContext';
import BypassConfigModal from '../components/bypass/BypassConfigModal';
import ConfirmModal from '../components/ConfirmModal';
import InfoModal from '../components/InfoModal';
import LoadingSpinner from '../components/LoadingSpinner';

interface ConfirmAction {
    type: 'delete' | 'generate';
    config: BypassConfigResponse;
}

const HTTP_METHOD_COLORS: Record<string, string> = {
    GET: 'bg-emerald-100 text-emerald-700',
    POST: 'bg-blue-100 text-blue-700',
    PUT: 'bg-amber-100 text-amber-700',
    DELETE: 'bg-red-100 text-red-700',
};

export default function BypassConfig() {
    const { showToast } = useToastContext();

    const [configs, setConfigs] = useState<BypassConfigResponse[]>([]);
    const [loading, setLoading] = useState(true);
    const [webclientBeans, setWebclientBeans] = useState<WebClientBeanInfo[]>([]);

    const [modalOpen, setModalOpen] = useState(false);
    const [editConfig, setEditConfig] = useState<BypassConfigResponse | null>(null);

    const [confirmAction, setConfirmAction] = useState<ConfirmAction | null>(null);
    const [generationResult, setGenerationResult] = useState<CodeGenerationResult | null>(null);

    const loadConfigs = useCallback(async () => {
        try {
            const res = await bypassApi.getConfigs();
            setConfigs(res.data ?? []);
        } catch (err) {
            showToast('Bypass API 목록 조회 실패', 'error');
            console.error(err);
        } finally {
            setLoading(false);
        }
    }, [showToast]);

    useEffect(() => {
        loadConfigs();
        bypassApi.getWebclientBeans()
            .then((res) => setWebclientBeans(res.data ?? []))
            .catch((err) => console.error(err));
    }, [loadConfigs]);

    const handleCreate = () => {
        setEditConfig(null);
        setModalOpen(true);
    };

    const handleEdit = (config: BypassConfigResponse) => {
        setEditConfig(config);
        setModalOpen(true);
    };

    const handleSave = async (data: BypassConfigRequest) => {
        if (editConfig) {
            await bypassApi.updateConfig(editConfig.id, data);
            showToast('Bypass API가 수정되었습니다.', 'success');
        } else {
            await bypassApi.createConfig(data);
            showToast('Bypass API가 등록되었습니다.', 'success');
        }
        await loadConfigs();
    };

    const handleDeleteConfirm = async () => {
        if (!confirmAction || confirmAction.type !== 'delete') return;
        try {
            await bypassApi.deleteConfig(confirmAction.config.id);
            showToast('Bypass API가 삭제되었습니다.', 'success');
            await loadConfigs();
        } catch (err) {
            showToast('삭제 실패', 'error');
            console.error(err);
        } finally {
            setConfirmAction(null);
        }
    };

    const handleGenerateConfirm = async () => {
        if (!confirmAction || confirmAction.type !== 'generate') return;
        const targetConfig = confirmAction.config;
        setConfirmAction(null);
        try {
            const res = await bypassApi.generateCode(targetConfig.id, targetConfig.generated);
            setGenerationResult(res.data);
            showToast('코드가 생성되었습니다.', 'success');
            await loadConfigs();
        } catch (err) {
            showToast('코드 생성 실패', 'error');
            console.error(err);
        }
    };

    if (loading) return <LoadingSpinner />;

    return (
        <div className="space-y-6">
            {/* 헤더 */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold text-wing-text">Bypass API 관리</h1>
                    <p className="mt-1 text-sm text-wing-muted">
                        외부 Maritime API를 직접 프록시하는 Bypass API를 등록하고 코드를 생성합니다.
                    </p>
                </div>
                <button
                    type="button"
                    onClick={handleCreate}
                    className="px-4 py-2 text-sm font-medium text-white bg-wing-accent hover:bg-wing-accent/80 rounded-lg transition-colors"
                >
                    + 새 API 등록
                </button>
            </div>

            {/* 카드 그리드 */}
            {configs.length === 0 ? (
                <div className="py-16 text-center text-wing-muted border border-dashed border-wing-border rounded-xl bg-wing-card">
                    <p className="text-base font-medium mb-1">등록된 BYPASS API가 없습니다.</p>
                    <p className="text-sm">위 버튼을 눌러 새 API를 등록하세요.</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {configs.map((config) => (
                        <div
                            key={config.id}
                            className="bg-wing-card border border-wing-border rounded-xl p-5 flex flex-col gap-3 hover:border-wing-accent/40 transition-colors"
                        >
                            {/* 카드 헤더 */}
                            <div className="flex items-start justify-between gap-2">
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold text-wing-text truncate">{config.displayName}</p>
                                    <p className="text-xs text-wing-muted font-mono mt-0.5">{config.domainName}</p>
                                </div>
                                <span
                                    className={[
                                        'shrink-0 px-2 py-0.5 text-xs font-semibold rounded-full',
                                        config.generated
                                            ? 'bg-emerald-100 text-emerald-700'
                                            : 'bg-wing-card text-wing-muted border border-wing-border',
                                    ].join(' ')}
                                >
                                    {config.generated ? '생성 완료' : '미생성'}
                                </span>
                            </div>

                            {/* 카드 정보 */}
                            <div className="space-y-1.5">
                                <div className="flex items-center gap-2">
                                    <span
                                        className={[
                                            'px-1.5 py-0.5 text-xs font-bold rounded',
                                            HTTP_METHOD_COLORS[config.httpMethod] ?? 'bg-wing-card text-wing-muted',
                                        ].join(' ')}
                                    >
                                        {config.httpMethod}
                                    </span>
                                    <span className="text-xs text-wing-muted font-mono truncate">
                                        {config.externalPath}
                                    </span>
                                </div>
                                <p className="text-xs text-wing-muted">
                                    <span className="font-medium text-wing-text">WebClient:</span>{' '}
                                    {config.webclientBean}
                                </p>
                                {config.description && (
                                    <p className="text-xs text-wing-muted line-clamp-2">{config.description}</p>
                                )}
                            </div>

                            {/* 카드 액션 */}
                            <div className="flex gap-2 pt-1 border-t border-wing-border mt-auto">
                                <button
                                    type="button"
                                    onClick={() => handleEdit(config)}
                                    className="flex-1 py-1.5 text-xs font-medium text-wing-text bg-wing-surface hover:bg-wing-hover border border-wing-border rounded-lg transition-colors"
                                >
                                    수정
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setConfirmAction({ type: 'generate', config })}
                                    className="flex-1 py-1.5 text-xs font-medium text-white bg-wing-accent hover:bg-wing-accent/80 rounded-lg transition-colors"
                                >
                                    {config.generated ? '재생성' : '코드 생성'}
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setConfirmAction({ type: 'delete', config })}
                                    className="py-1.5 px-3 text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 rounded-lg transition-colors"
                                >
                                    삭제
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* 등록/수정 모달 */}
            <BypassConfigModal
                open={modalOpen}
                editConfig={editConfig}
                webclientBeans={webclientBeans}
                onSave={handleSave}
                onClose={() => setModalOpen(false)}
            />

            {/* 삭제 확인 모달 */}
            <ConfirmModal
                open={confirmAction?.type === 'delete'}
                title="삭제 확인"
                message={`"${confirmAction?.config.displayName}"을(를) 정말 삭제하시겠습니까?\n삭제된 데이터는 복구할 수 없습니다.`}
                confirmLabel="삭제"
                confirmColor="bg-red-500 hover:bg-red-600"
                onConfirm={handleDeleteConfirm}
                onCancel={() => setConfirmAction(null)}
            />

            {/* 코드 생성 확인 모달 */}
            <ConfirmModal
                open={confirmAction?.type === 'generate'}
                title={confirmAction?.config.generated ? '코드 재생성 확인' : '코드 생성 확인'}
                message={
                    confirmAction?.config.generated
                        ? `"${confirmAction?.config.displayName}" 코드를 재생성합니다.\n기존 생성된 파일이 덮어씌워집니다. 계속하시겠습니까?`
                        : `"${confirmAction?.config.displayName}" 코드를 생성합니다.\n계속하시겠습니까?`
                }
                confirmLabel={confirmAction?.config.generated ? '재생성' : '생성'}
                onConfirm={handleGenerateConfirm}
                onCancel={() => setConfirmAction(null)}
            />

            {/* 코드 생성 결과 모달 */}
            <InfoModal
                open={generationResult !== null}
                title="코드 생성 완료"
                onClose={() => setGenerationResult(null)}
            >
                {generationResult && (
                    <div className="space-y-3">
                        <p className="text-sm text-wing-text">{generationResult.message}</p>
                        <div className="bg-wing-card rounded-lg p-3 space-y-2">
                            <p className="text-xs font-semibold text-wing-text mb-1">생성된 파일</p>
                            {[
                                { label: 'Controller', path: generationResult.controllerPath },
                                { label: 'Service', path: generationResult.servicePath },
                                { label: 'DTO', path: generationResult.dtoPath },
                            ].map(({ label, path }) => (
                                <div key={label} className="flex gap-2 text-xs">
                                    <span className="w-20 font-medium text-wing-accent shrink-0">{label}</span>
                                    <span className="font-mono text-wing-muted break-all">{path}</span>
                                </div>
                            ))}
                        </div>
                        <div className="flex items-start gap-2 bg-amber-50 text-amber-700 rounded-lg p-3 text-xs">
                            <span className="shrink-0">⚠</span>
                            <span>서버를 재시작하면 새 API가 활성화됩니다.</span>
                        </div>
                    </div>
                )}
            </InfoModal>
        </div>
    );
}
