@extends('layouts.app')

@section('title', 'AI 토큰 사용량')

@push('styles')
<style>
    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 16px 20px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    }
    .stat-card .label { font-size: 13px; color: #6b7280; margin-bottom: 4px; }
    .stat-card .value { font-size: 22px; font-weight: 700; color: #111827; }
    .stat-card .sub { font-size: 12px; color: #9ca3af; margin-top: 2px; }

    .filter-bar {
        background: white;
        border-radius: 12px;
        padding: 16px 20px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        display: flex;
        gap: 12px;
        align-items: end;
        flex-wrap: wrap;
    }
    .filter-bar label { display: block; font-size: 12px; color: #6b7280; margin-bottom: 4px; font-weight: 500; }
    .filter-bar select,
    .filter-bar input {
        border: 1px solid #d1d5db;
        border-radius: 8px;
        padding: 6px 10px;
        font-size: 13px;
        min-width: 140px;
    }
    .filter-bar button {
        padding: 7px 16px;
        border-radius: 8px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.15s;
    }

    .data-table { width: 100%; border-collapse: collapse; }
    .data-table th {
        background: #f9fafb;
        font-size: 12px;
        font-weight: 600;
        color: #6b7280;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 10px 12px;
        text-align: left;
        border-bottom: 1px solid #e5e7eb;
    }
    .data-table td {
        padding: 10px 12px;
        font-size: 13px;
        color: #374151;
        border-bottom: 1px solid #f3f4f6;
    }
    .data-table tr:hover td { background: #f9fafb; }
    .data-table .num { text-align: right; font-variant-numeric: tabular-nums; }

    .pagination-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
    }
    .pagination-bar button {
        padding: 6px 12px;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        background: white;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.15s;
    }
    .pagination-bar button:disabled { opacity: 0.4; cursor: not-allowed; }
    .pagination-bar button:not(:disabled):hover { background: #f3f4f6; }

    .badge {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 11px;
        font-weight: 500;
    }
    .badge-blue { background: #dbeafe; color: #1d4ed8; }
    .badge-green { background: #dcfce7; color: #16a34a; }
    .badge-purple { background: #f3e8ff; color: #7c3aed; }
    .badge-orange { background: #ffedd5; color: #c2410c; }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #9ca3af;
    }
    .empty-state svg { margin: 0 auto 12px; }

    .modal-overlay {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 50;
    }
    .modal-content {
        background: white;
        border-radius: 16px;
        width: 90%;
        max-width: 800px;
        max-height: 85vh;
        overflow-y: auto;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
    }
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 24px;
        border-bottom: 1px solid #e5e7eb;
    }
    .modal-header h2 { font-size: 18px; font-weight: 700; color: #111827; }
    .modal-body { padding: 24px; }
    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 8px;
        padding: 16px 24px;
        border-top: 1px solid #e5e7eb;
    }

    .pricing-table { width: 100%; border-collapse: collapse; }
    .pricing-table th {
        font-size: 12px;
        font-weight: 600;
        color: #6b7280;
        padding: 8px 10px;
        text-align: left;
        border-bottom: 2px solid #e5e7eb;
        white-space: nowrap;
    }
    .pricing-table td {
        padding: 8px 10px;
        border-bottom: 1px solid #f3f4f6;
        vertical-align: middle;
    }
    .pricing-table input[type="text"],
    .pricing-table input[type="number"] {
        border: 1px solid #d1d5db;
        border-radius: 6px;
        padding: 5px 8px;
        font-size: 13px;
        width: 100%;
        min-width: 80px;
    }
    .pricing-table input:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59,130,246,0.2);
    }

    .toast {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        z-index: 60;
        animation: slideIn 0.3s ease;
    }
    .toast-success { background: #dcfce7; color: #16a34a; border: 1px solid #bbf7d0; }
    .toast-error { background: #fee2e2; color: #dc2626; border: 1px solid #fecaca; }
    @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
</style>
@endpush

@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="ai-token-usage-root"></div>
@endsection

@push('scripts')
@include('partials.react-cdn')
<script src="https://unpkg.com/lucide@0.469.0?v={{ time() }}"></script>
@verbatim
<script type="text/babel">
const { useState, useEffect, useRef } = React;

const createIcon = (name) => {
    const _def=((n)=>{const a={'check-circle':'CircleCheck','alert-circle':'CircleAlert','alert-triangle':'TriangleAlert','clipboard-check':'ClipboardCheck','arrow-up-circle':'CircleArrowUp','arrow-down-circle':'CircleArrowDown'};if(a[n]&&lucide[a[n]])return lucide[a[n]];const p=n.split('-').map(w=>w.charAt(0).toUpperCase()+w.slice(1)).join('');return lucide[p]||(lucide.icons&&lucide.icons[n])||null;})(name);
    const _c = s => s.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
    return ({ className = "w-5 h-5", ...props }) => {
        if (!_def) return null;
        const [, attrs, children = []] = _def;
        const sp = { className };
        Object.entries(attrs).forEach(([k, v]) => { sp[_c(k)] = v; });
        Object.assign(sp, props);
        return React.createElement("svg", sp, ...children.map(([tag, ca], i) => {
            const cp = { key: i };
            if (ca) Object.entries(ca).forEach(([k, v]) => { cp[_c(k)] = v; });
            return React.createElement(tag, cp);
        }));
    };
};

const BrainCircuit = createIcon('brain-circuit');
const Search = createIcon('search');
const RotateCcw = createIcon('rotate-ccw');
const ChevronLeft = createIcon('chevron-left');
const ChevronRight = createIcon('chevron-right');
const Zap = createIcon('zap');
const DollarSign = createIcon('dollar-sign');
const Hash = createIcon('hash');
const ArrowUpDown = createIcon('arrow-up-down');
const Settings = createIcon('settings');
const X = createIcon('x');
const Save = createIcon('save');

const getCategory = (menuName) => {
    if (!menuName) return '-';
    if (menuName.startsWith('AI음성녹음')) return 'AI음성녹음';
    if (menuName.startsWith('회의록')) return '회의록';
    if (menuName.includes('명함')) return '명함OCR';
    if (menuName.includes('사업자등록증')) return '사업자등록증OCR';
    return menuName;
};

const fmtDuration = (sec) => { if (!sec || sec <= 0) return ''; const m = Math.floor(sec/60); const s = sec%60; return m > 0 ? `${m}분 ${s}초` : `${s}초`; };

const fmt = (n) => n != null ? Number(n).toLocaleString() : '0';
const fmtUsd = (n) => n != null ? '$' + Number(n).toFixed(4) : '$0.0000';
const fmtKrw = (n) => n != null ? Number(n).toLocaleString('ko-KR', { maximumFractionDigits: 0 }) + '원' : '0원';

const PROVIDER_LABELS = {
    'gemini': { label: 'Gemini', type: 'token' },
    'claude': { label: 'Claude', type: 'token' },
    'google-stt': { label: 'Google STT', type: 'unit' },
    'google-gcs': { label: 'Google GCS', type: 'unit' },
};

function PricingModal({ show, onClose, onSaved }) {
    const [configs, setConfigs] = useState([]);
    const [loading, setLoading] = useState(false);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        if (show) {
            setLoading(true);
            fetch('/system/ai-token-usage/pricing')
                .then(r => r.json())
                .then(json => { if (json.success) setConfigs(json.data); })
                .catch(err => console.error('단가 조회 실패:', err))
                .finally(() => setLoading(false));
        }
    }, [show]);

    const updateField = (idx, field, value) => {
        setConfigs(prev => {
            const next = [...prev];
            next[idx] = { ...next[idx], [field]: value };
            return next;
        });
    };

    const handleSave = async () => {
        setSaving(true);
        try {
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
            const res = await fetch('/system/ai-token-usage/pricing', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                body: JSON.stringify({ configs }),
            });
            const json = await res.json();
            if (json.success) {
                onSaved('단가 설정이 저장되었습니다.');
                onClose();
            } else {
                onSaved(json.message || '저장 실패', true);
            }
        } catch (err) {
            onSaved('저장 중 오류가 발생했습니다.', true);
        } finally {
            setSaving(false);
        }
    };

    if (!show) return null;

    return (
        <div className="modal-overlay" onClick={onClose}>
            <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                    <h2 className="flex items-center gap-2">
                        <Settings className="w-5 h-5" />
                        AI 토큰 단가 설정
                    </h2>
                    <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded-lg transition">
                        <X className="w-5 h-5" />
                    </button>
                </div>
                <div className="modal-body">
                    {loading ? (
                        <div className="text-center py-8 text-gray-400">
                            <div className="animate-spin inline-block w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full mb-2"></div>
                            <p>로딩 중...</p>
                        </div>
                    ) : (
                        <>
                            <div className="overflow-x-auto">
                                <table className="pricing-table">
                                    <thead>
                                        <tr>
                                            <th>제공자</th>
                                            <th>모델명</th>
                                            <th>입력 단가<br/><span style={{fontWeight:400,fontSize:11}}>$/1M tokens</span></th>
                                            <th>출력 단가<br/><span style={{fontWeight:400,fontSize:11}}>$/1M tokens</span></th>
                                            <th>단위 가격<br/><span style={{fontWeight:400,fontSize:11}}>$ per unit</span></th>
                                            <th>환율<br/><span style={{fontWeight:400,fontSize:11}}>USD→KRW</span></th>
                                            <th>설명</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {configs.map((c, idx) => {
                                            const info = PROVIDER_LABELS[c.provider] || { label: c.provider, type: 'token' };
                                            const isUnit = info.type === 'unit';
                                            return (
                                                <tr key={c.id}>
                                                    <td>
                                                        <span className="badge badge-purple">{info.label}</span>
                                                    </td>
                                                    <td>
                                                        <input type="text" value={c.model_name}
                                                            onChange={e => updateField(idx, 'model_name', e.target.value)} />
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.0001" value={c.input_price_per_million}
                                                            disabled={isUnit}
                                                            style={isUnit ? {background:'#f3f4f6',color:'#9ca3af'} : {}}
                                                            onChange={e => updateField(idx, 'input_price_per_million', parseFloat(e.target.value) || 0)} />
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.0001" value={c.output_price_per_million}
                                                            disabled={isUnit}
                                                            style={isUnit ? {background:'#f3f4f6',color:'#9ca3af'} : {}}
                                                            onChange={e => updateField(idx, 'output_price_per_million', parseFloat(e.target.value) || 0)} />
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.000001" value={c.unit_price}
                                                            disabled={!isUnit}
                                                            style={!isUnit ? {background:'#f3f4f6',color:'#9ca3af'} : {}}
                                                            onChange={e => updateField(idx, 'unit_price', parseFloat(e.target.value) || 0)} />
                                                        {isUnit && c.unit_description && (
                                                            <div style={{fontSize:11,color:'#9ca3af',marginTop:2}}>{c.unit_description}</div>
                                                        )}
                                                    </td>
                                                    <td>
                                                        <input type="number" step="0.01" value={c.exchange_rate}
                                                            onChange={e => updateField(idx, 'exchange_rate', parseFloat(e.target.value) || 0)} />
                                                    </td>
                                                    <td>
                                                        <input type="text" value={c.description || ''}
                                                            onChange={e => updateField(idx, 'description', e.target.value)} />
                                                    </td>
                                                </tr>
                                            );
                                        })}
                                    </tbody>
                                </table>
                            </div>
                            <div style={{marginTop:12,padding:'10px 12px',background:'#fffbeb',borderRadius:8,fontSize:12,color:'#92400e'}}>
                                * 토큰 기반 모델(Gemini, Claude)은 입력/출력 단가를, 단위 기반 서비스(STT, GCS)는 단위 가격을 수정하세요.
                                <br/>* 환율 변경 시 모든 모델에 동일하게 적용됩니다. 저장 후 새로운 요청부터 변경된 단가가 적용됩니다.
                            </div>
                        </>
                    )}
                </div>
                <div className="modal-footer">
                    <button onClick={onClose}
                        className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium transition">
                        취소
                    </button>
                    <button onClick={handleSave} disabled={saving || loading}
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium transition flex items-center gap-1 disabled:opacity-50">
                        <Save className="w-4 h-4" />
                        {saving ? '저장 중...' : '저장'}
                    </button>
                </div>
            </div>
        </div>
    );
}

function AiTokenUsageApp() {
    const [records, setRecords] = useState([]);
    const [stats, setStats] = useState({});
    const [filters, setFilters] = useState({ menu_names: [], tenants: [] });
    const [pagination, setPagination] = useState({ current_page: 1, last_page: 1, per_page: 20, total: 0 });
    const [loading, setLoading] = useState(true);
    const [showPricingModal, setShowPricingModal] = useState(false);
    const [toast, setToast] = useState(null);

    // 필터 상태
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const [startDate, setStartDate] = useState(firstDay.toISOString().split('T')[0]);
    const [endDate, setEndDate] = useState(today.toISOString().split('T')[0]);
    const [tenantId, setTenantId] = useState('');
    const [menuName, setMenuName] = useState('');
    const [page, setPage] = useState(1);

    const fetchData = async (p = 1) => {
        setLoading(true);
        try {
            const params = new URLSearchParams();
            if (startDate) params.set('start_date', startDate);
            if (endDate) params.set('end_date', endDate);
            if (tenantId) params.set('tenant_id', tenantId);
            if (menuName) params.set('menu_name', menuName);
            params.set('page', p);
            params.set('per_page', 20);

            const res = await fetch(`/system/ai-token-usage/list?${params}`);
            const json = await res.json();
            if (json.success) {
                setRecords(json.data);
                setStats(json.stats);
                setFilters(json.filters);
                setPagination(json.pagination);
                setPage(json.pagination.current_page);
            }
        } catch (err) {
            console.error('데이터 조회 실패:', err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchData(); }, []);

    const handleSearch = () => { fetchData(1); };
    const handleReset = () => {
        setStartDate(firstDay.toISOString().split('T')[0]);
        setEndDate(today.toISOString().split('T')[0]);
        setTenantId('');
        setMenuName('');
        setTimeout(() => fetchData(1), 0);
    };
    const goPage = (p) => { fetchData(p); };

    const showToast = (message, isError = false) => {
        setToast({ message, isError });
        setTimeout(() => setToast(null), 3000);
    };

    return (
        <div className="space-y-4">
            {/* Toast 알림 */}
            {toast && (
                <div className={`toast ${toast.isError ? 'toast-error' : 'toast-success'}`}>
                    {toast.message}
                </div>
            )}

            {/* 단가 설정 모달 */}
            <PricingModal
                show={showPricingModal}
                onClose={() => setShowPricingModal(false)}
                onSaved={(msg, isError) => showToast(msg, isError)}
            />

            {/* 페이지 헤더 */}
            <div className="flex justify-between items-center">
                <h1 className="text-2xl font-bold text-gray-800 flex items-center gap-2">
                    <BrainCircuit className="w-7 h-7" />
                    AI 토큰 사용량
                </h1>
                <button
                    onClick={() => setShowPricingModal(true)}
                    className="flex items-center gap-1.5 px-3 py-2 bg-white border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 hover:border-gray-400 transition shadow-sm"
                >
                    <Settings className="w-4 h-4" />
                    단가 설정
                </button>
            </div>

            {/* 통계 카드 */}
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                <div className="stat-card">
                    <div className="label">총 호출 수</div>
                    <div className="value">{fmt(stats.total_count)}</div>
                    <div className="sub">건</div>
                </div>
                <div className="stat-card">
                    <div className="label">입력 토큰</div>
                    <div className="value">{fmt(stats.total_prompt_tokens)}</div>
                    <div className="sub">tokens</div>
                </div>
                <div className="stat-card">
                    <div className="label">출력 토큰</div>
                    <div className="value">{fmt(stats.total_completion_tokens)}</div>
                    <div className="sub">tokens</div>
                </div>
                <div className="stat-card">
                    <div className="label">전체 토큰</div>
                    <div className="value">{fmt(stats.total_total_tokens)}</div>
                    <div className="sub">tokens</div>
                </div>
                <div className="stat-card">
                    <div className="label">총 비용 (USD)</div>
                    <div className="value">{fmtUsd(stats.total_cost_usd)}</div>
                    <div className="sub">달러</div>
                </div>
                <div className="stat-card">
                    <div className="label">총 비용 (KRW)</div>
                    <div className="value">{fmtKrw(stats.total_cost_krw)}</div>
                    <div className="sub">원</div>
                </div>
            </div>

            {/* 필터 바 */}
            <div className="filter-bar">
                <div>
                    <label>시작일</label>
                    <input type="date" value={startDate} onChange={e => setStartDate(e.target.value)} />
                </div>
                <div>
                    <label>종료일</label>
                    <input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} />
                </div>
                <div>
                    <label>테넌트</label>
                    <select value={tenantId} onChange={e => setTenantId(e.target.value)}>
                        <option value="">전체</option>
                        {filters.tenants.map(t => (
                            <option key={t.id} value={t.id}>{t.name}</option>
                        ))}
                    </select>
                </div>
                <div>
                    <label>호출 메뉴</label>
                    <select value={menuName} onChange={e => setMenuName(e.target.value)}>
                        <option value="">전체</option>
                        {filters.menu_names.map(m => (
                            <option key={m} value={m}>{m}</option>
                        ))}
                    </select>
                </div>
                <button
                    onClick={handleSearch}
                    className="bg-blue-600 text-white hover:bg-blue-700 flex items-center gap-1"
                >
                    <Search className="w-4 h-4" /> 조회
                </button>
                <button
                    onClick={handleReset}
                    className="bg-gray-100 text-gray-700 hover:bg-gray-200 flex items-center gap-1"
                >
                    <RotateCcw className="w-4 h-4" /> 초기화
                </button>
            </div>

            {/* 데이터 테이블 */}
            <div className="bg-white rounded-xl shadow-sm overflow-hidden">
                {loading ? (
                    <div className="text-center py-16 text-gray-400">
                        <div className="animate-spin inline-block w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mb-3"></div>
                        <p>데이터를 불러오는 중...</p>
                    </div>
                ) : records.length === 0 ? (
                    <div className="empty-state">
                        <BrainCircuit className="w-12 h-12 text-gray-300" />
                        <p className="text-lg font-medium text-gray-500 mt-2">사용 내역이 없습니다</p>
                        <p className="text-sm">AI 기능을 사용하면 토큰 사용량이 기록됩니다.</p>
                    </div>
                ) : (
                    <>
                        <div className="overflow-x-auto">
                            <table className="data-table">
                                <thead>
                                    <tr>
                                        <th>테넌트</th>
                                        <th>사용일시</th>
                                        <th>카테고리</th>
                                        <th>호출메뉴</th>
                                        <th>모델</th>
                                        <th>녹음시간</th>
                                        <th className="num">입력토큰</th>
                                        <th className="num">출력토큰</th>
                                        <th className="num">전체토큰</th>
                                        <th className="num">비용(USD)</th>
                                        <th className="num">비용(KRW)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {records.map(r => (
                                        <tr key={r.id}>
                                            <td>
                                                <span className="badge badge-blue">{r.tenant_id}</span>
                                                {' '}{r.tenant_name}
                                            </td>
                                            <td>{r.created_at}</td>
                                            <td><span className="badge badge-orange">{getCategory(r.menu_name)}</span></td>
                                            <td><span className="badge badge-green">{r.menu_name}</span></td>
                                            <td><span className="badge badge-purple">{r.model}</span></td>
                                            <td>{r.model === 'google-speech-to-text' ? fmtDuration(r.prompt_tokens) : ''}</td>
                                            <td className="num">{fmt(r.prompt_tokens)}</td>
                                            <td className="num">{fmt(r.completion_tokens)}</td>
                                            <td className="num font-semibold">{fmt(r.total_tokens)}</td>
                                            <td className="num">{fmtUsd(r.cost_usd)}</td>
                                            <td className="num font-semibold">{fmtKrw(r.cost_krw)}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {/* 페이지네이션 */}
                        <div className="pagination-bar px-4">
                            <span className="text-sm text-gray-500">
                                총 {fmt(pagination.total)}건 (페이지 {pagination.current_page}/{pagination.last_page})
                            </span>
                            <div className="flex gap-2">
                                <button
                                    disabled={pagination.current_page <= 1}
                                    onClick={() => goPage(pagination.current_page - 1)}
                                    className="flex items-center gap-1"
                                >
                                    <ChevronLeft className="w-4 h-4" /> 이전
                                </button>
                                <button
                                    disabled={pagination.current_page >= pagination.last_page}
                                    onClick={() => goPage(pagination.current_page + 1)}
                                    className="flex items-center gap-1"
                                >
                                    다음 <ChevronRight className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    </>
                )}
            </div>
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('ai-token-usage-root')).render(<AiTokenUsageApp />);
</script>
@endverbatim
@endpush
