import { useState, useEffect, useCallback, useMemo } 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;
}

type ViewMode = 'card' | 'table';

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 [viewMode, setViewMode] = useState<ViewMode>('table');
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedDomain, setSelectedDomain] = useState('');

    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 [codeGenEnabled, setCodeGenEnabled] = useState(true);

    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));
        fetch('/snp-api/api/bypass-config/environment')
            .then(res => res.json())
            .then(res => setCodeGenEnabled(res.data?.codeGenerationEnabled ?? true))
            .catch(() => {});
    }, [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);
        }
    };

    const domainNames = useMemo(() => {
        const names = [...new Set(configs.map((c) => c.domainName))];
        return names.sort();
    }, [configs]);

    const filteredConfigs = useMemo(() => {
        return configs.filter((c) => {
            const matchesSearch =
                !searchTerm.trim() ||
                c.domainName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                c.displayName.toLowerCase().includes(searchTerm.toLowerCase());
            const matchesDomain = !selectedDomain || c.domainName === selectedDomain;
            return matchesSearch && matchesDomain;
        });
    }, [configs, searchTerm, selectedDomain]);

    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>

            {/* 검색 + 뷰 전환 */}
            <div className="bg-wing-surface rounded-xl shadow-md p-4">
                <div className="flex gap-3 items-center flex-wrap">
                    {/* 검색 */}
                    <div className="relative flex-1 min-w-[200px]">
                        <span className="absolute inset-y-0 left-3 flex items-center text-wing-muted">
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                                />
                            </svg>
                        </span>
                        <input
                            type="text"
                            placeholder="도메인명, 표시명으로 검색..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full pl-10 pr-4 py-2 border border-wing-border rounded-lg text-sm
                                focus:ring-2 focus:ring-wing-accent focus:border-wing-accent outline-none bg-wing-surface text-wing-text"
                        />
                        {searchTerm && (
                            <button
                                type="button"
                                onClick={() => setSearchTerm('')}
                                className="absolute inset-y-0 right-3 flex items-center text-wing-muted hover:text-wing-text"
                            >
                                <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>

                    {/* 도메인 드롭다운 필터 */}
                    <select
                        value={selectedDomain}
                        onChange={(e) => setSelectedDomain(e.target.value)}
                        className="px-3 py-2 text-sm rounded-lg border border-wing-border bg-wing-surface text-wing-text"
                    >
                        <option value="">전체 도메인</option>
                        {domainNames.map((name) => (
                            <option key={name} value={name}>{name}</option>
                        ))}
                    </select>

                    {/* 뷰 전환 토글 */}
                    <div className="flex rounded-lg border border-wing-border overflow-hidden">
                        <button
                            type="button"
                            onClick={() => setViewMode('table')}
                            title="테이블 보기"
                            className={`px-3 py-2 transition-colors ${
                                viewMode === 'table'
                                    ? 'bg-wing-accent text-white'
                                    : 'bg-wing-surface text-wing-muted hover:text-wing-text'
                            }`}
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                            </svg>
                        </button>
                        <button
                            type="button"
                            onClick={() => setViewMode('card')}
                            title="카드 보기"
                            className={`px-3 py-2 transition-colors border-l border-wing-border ${
                                viewMode === 'card'
                                    ? 'bg-wing-accent text-white'
                                    : 'bg-wing-surface text-wing-muted hover:text-wing-text'
                            }`}
                        >
                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"
                                />
                            </svg>
                        </button>
                    </div>
                </div>

                {(searchTerm || selectedDomain) && (
                    <p className="mt-2 text-xs text-wing-muted">
                        {filteredConfigs.length}개 API 검색됨
                    </p>
                )}
            </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>
            ) : filteredConfigs.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">검색 결과가 없습니다.</p>
                    <p className="text-sm">다른 검색어를 사용해 보세요.</p>
                </div>
            ) : viewMode === 'card' ? (
                /* 카드 뷰 */
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredConfigs.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 })}
                                    disabled={!codeGenEnabled}
                                    title={!codeGenEnabled ? '운영 환경에서는 코드 생성이 불가합니다' : ''}
                                    className={`flex-1 py-1.5 text-xs font-medium rounded-lg transition-colors ${
                                        codeGenEnabled
                                            ? 'text-white bg-wing-accent hover:bg-wing-accent/80'
                                            : 'text-wing-muted bg-wing-card cursor-not-allowed'
                                    }`}
                                >
                                    {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>
            ) : (
                /* 테이블 뷰 */
                <div className="bg-wing-surface rounded-xl shadow-md overflow-hidden">
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b border-wing-border bg-wing-card">
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        도메인명
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        표시명
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        HTTP 메서드
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        WebClient
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        외부 경로
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        생성 상태
                                    </th>
                                    <th className="text-left px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        등록일
                                    </th>
                                    <th className="text-right px-4 py-3 text-xs font-semibold text-wing-muted uppercase tracking-wider">
                                        액션
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-wing-border">
                                {filteredConfigs.map((config) => (
                                    <tr key={config.id} className="hover:bg-wing-hover transition-colors">
                                        <td className="px-4 py-3 font-mono text-xs text-wing-text">
                                            {config.domainName}
                                        </td>
                                        <td className="px-4 py-3 font-medium text-wing-text">
                                            {config.displayName}
                                        </td>
                                        <td className="px-4 py-3">
                                            <span
                                                className={[
                                                    'px-2 py-0.5 text-xs font-bold rounded',
                                                    HTTP_METHOD_COLORS[config.httpMethod] ?? 'bg-wing-card text-wing-muted',
                                                ].join(' ')}
                                            >
                                                {config.httpMethod}
                                            </span>
                                        </td>
                                        <td className="px-4 py-3 text-xs text-wing-muted">
                                            {config.webclientBean}
                                        </td>
                                        <td className="px-4 py-3 font-mono text-xs text-wing-muted max-w-[200px] truncate">
                                            {config.externalPath}
                                        </td>
                                        <td className="px-4 py-3">
                                            <span
                                                className={[
                                                    '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>
                                        </td>
                                        <td className="px-4 py-3 text-xs text-wing-muted whitespace-nowrap">
                                            {config.createdAt
                                                ? new Date(config.createdAt).toLocaleDateString('ko-KR')
                                                : '-'}
                                        </td>
                                        <td className="px-4 py-3">
                                            <div className="flex justify-end gap-2">
                                                <button
                                                    type="button"
                                                    onClick={() => handleEdit(config)}
                                                    className="px-3 py-1.5 text-xs font-medium text-wing-text bg-wing-card hover:bg-wing-hover border border-wing-border rounded-lg transition-colors"
                                                >
                                                    수정
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => setConfirmAction({ type: 'generate', config })}
                                                    disabled={!codeGenEnabled}
                                                    title={!codeGenEnabled ? '운영 환경에서는 코드 생성이 불가합니다' : ''}
                                                    className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-colors ${
                                                        codeGenEnabled
                                                            ? 'text-white bg-wing-accent hover:bg-wing-accent/80'
                                                            : 'text-wing-muted bg-wing-card cursor-not-allowed'
                                                    }`}
                                                >
                                                    {config.generated ? '재생성' : '코드 생성'}
                                                </button>
                                                <button
                                                    type="button"
                                                    onClick={() => setConfirmAction({ type: 'delete', config })}
                                                    className="px-3 py-1.5 text-xs font-medium text-red-500 hover:bg-red-50 border border-red-200 rounded-lg transition-colors"
                                                >
                                                    삭제
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </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>
                            <div className="flex gap-2 text-xs">
                                <span className="w-20 font-medium text-wing-accent shrink-0">Controller</span>
                                <span className="font-mono text-wing-muted break-all">{generationResult.controllerPath}</span>
                            </div>
                            {generationResult.servicePaths.map((path, idx) => (
                                <div key={`service-${idx}`} className="flex gap-2 text-xs">
                                    <span className="w-20 font-medium text-wing-accent shrink-0">
                                        Service {generationResult.servicePaths.length > 1 ? idx + 1 : ''}
                                    </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">&#9888;</span>
                            <span>서버를 재시작하면 새 API가 활성화됩니다.</span>
                        </div>
                    </div>
                )}
            </InfoModal>
        </div>
    );
}
