@extends('layouts.app')

@section('title', '계좌거래내역')

@push('styles')
<style>
    @media print { .no-print { display: none !important; } }
</style>
@endpush

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

@push('scripts')
@include('partials.react-cdn')
<script src="https://unpkg.com/lucide@0.469.0?v={{ time() }}"></script>
<script>
// SVG 속성 에러 진단: setAttribute 호출을 가로채서 따옴표가 포함된 값을 추적
(function() {
    var origSetAttr = Element.prototype.setAttribute;
    Element.prototype.setAttribute = function(name, value) {
        var s = String(value);
        if ((name === 'viewBox' || name === 'd') && s.charAt(0) === '"') {
            console.error('[SVG-DIAG] Bad ' + name + '=' + JSON.stringify(s), 'tag=' + this.tagName, new Error().stack);
        }
        return origSetAttr.call(this, name, value);
    };
})();
</script>
@verbatim
<script type="text/babel">
const { useState, useRef, useEffect } = 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 ArrowUpDown = createIcon('arrow-up-down');
const ArrowUpCircle = createIcon('arrow-up-circle');
const ArrowDownCircle = createIcon('arrow-down-circle');
const Search = createIcon('search');
const Download = createIcon('download');
const RefreshCw = createIcon('refresh-cw');
const Filter = createIcon('filter');
const Loader2 = createIcon('loader-2');

function AccountTransactions() {
    const [transactions, setTransactions] = useState([]);
    const [accounts, setAccounts] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    const now = new Date();
    const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
    const [dateRange, setDateRange] = useState({
        start: firstDay.toISOString().split('T')[0],
        end: now.toISOString().split('T')[0]
    });

    const [searchTerm, setSearchTerm] = useState('');
    const [filterAccount, setFilterAccount] = useState('');
    const [filterType, setFilterType] = useState('all');

    const formatCurrency = (num) => num ? Number(num).toLocaleString() : '0';

    // 날짜 포맷: 20260121 → 2026-01-21
    const formatDate = (d) => {
        if (!d || d.length < 8) return d || '';
        return d.substring(0, 4) + '-' + d.substring(4, 6) + '-' + d.substring(6, 8);
    };

    // 계좌 목록 조회
    const fetchAccounts = async () => {
        try {
            const res = await fetch('/barobill/eaccount/accounts');
            const data = await res.json();
            if (data.success && data.accounts) {
                setAccounts(data.accounts);
            }
        } catch (err) {
            console.error('계좌 목록 조회 실패:', err);
        }
    };

    // 거래내역 조회
    const fetchTransactions = async () => {
        setLoading(true);
        setError(null);
        try {
            const startDate = (dateRange.start || '').replace(/-/g, '');
            const endDate = (dateRange.end || '').replace(/-/g, '');
            const params = new URLSearchParams({
                startDate,
                endDate,
                limit: '1000',
            });
            if (filterAccount) {
                params.set('accountNum', filterAccount);
            }
            const res = await fetch(`/barobill/eaccount/transactions?${params}`);
            const data = await res.json();
            if (data.success && data.data) {
                const logs = data.data.logs || [];
                const mapped = logs.map((log, idx) => ({
                    id: idx + 1,
                    date: formatDate(log.transDate),
                    time: log.transTime ? (log.transTime.substring(0,2) + ':' + log.transTime.substring(2,4)) : '',
                    accountName: log.bankName || '',
                    accountNo: log.bankAccountNum || '',
                    type: log.deposit > 0 ? 'deposit' : 'withdrawal',
                    category: log.accountName || '',
                    description: log.summary || '',
                    amount: log.deposit > 0 ? log.deposit : log.withdraw,
                    balance: log.balance,
                    memo: log.memo || '',
                    cast: log.cast || '',
                }));
                setTransactions(mapped);
            } else {
                setError(data.error || '조회에 실패했습니다.');
                setTransactions([]);
            }
        } catch (err) {
            console.error('거래내역 조회 실패:', err);
            setError('서버 연결에 실패했습니다.');
            setTransactions([]);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchAccounts(); }, []);
    useEffect(() => { fetchTransactions(); }, [dateRange.start, dateRange.end, filterAccount]);

    const filteredTransactions = transactions.filter(item => {
        const matchesSearch = (item.description || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (item.accountName || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                             (item.cast || '').toLowerCase().includes(searchTerm.toLowerCase());
        const matchesType = filterType === 'all' || item.type === filterType;
        return matchesSearch && matchesType;
    });

    const totalDeposit = filteredTransactions.filter(t => t.type === 'deposit').reduce((sum, t) => sum + t.amount, 0);
    const totalWithdrawal = filteredTransactions.filter(t => t.type === 'withdrawal').reduce((sum, t) => sum + t.amount, 0);

    const handleDownload = () => {
        const rows = [['계좌거래내역'], [], ['날짜', '시간', '계좌', '계좌번호', '구분', '분류', '내용', '금액', '잔액', '메모'],
            ...filteredTransactions.map(item => [item.date, item.time, item.accountName, item.accountNo, getTypeLabel(item.type), item.category, item.description, item.amount, item.balance, item.memo])];
        const csvContent = rows.map(row => row.join(',')).join('\n');
        const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = `계좌거래내역_${dateRange.start}_${dateRange.end}.csv`; link.click();
    };

    const getTypeLabel = (type) => ({ 'deposit': '입금', 'withdrawal': '출금' }[type] || type);
    const getTypeStyle = (type) => ({ 'deposit': 'text-blue-600', 'withdrawal': 'text-red-600' }[type] || 'text-gray-600');
    const getTypeIcon = (type) => type === 'deposit' ? <ArrowDownCircle className="w-4 h-4 text-blue-500" /> : <ArrowUpCircle className="w-4 h-4 text-red-500" />;

    const resetFilters = () => {
        setSearchTerm('');
        setFilterAccount('');
        setFilterType('all');
        const now = new Date();
        const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
        setDateRange({ start: firstDay.toISOString().split('T')[0], end: now.toISOString().split('T')[0] });
    };

    return (
        <div className="bg-gray-50 min-h-screen">
            <header className="bg-white border-b border-gray-200 rounded-t-xl mb-6">
                <div className="px-6 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <div className="p-2 bg-blue-100 rounded-xl"><ArrowUpDown className="w-6 h-6 text-blue-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">계좌거래내역</h1><p className="text-sm text-gray-500">Account Transactions</p></div>
                    </div>
                    <div className="flex items-center gap-3">
                        <button onClick={handleDownload} className="flex items-center gap-2 px-4 py-2 text-gray-700 hover:bg-gray-100 rounded-lg"><Download className="w-4 h-4" /><span className="text-sm">Excel</span></button>
                    </div>
                </div>
            </header>

            {/* 요약 카드 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div className="bg-white rounded-xl border border-gray-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-gray-500">조회 건수</span><Filter className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{filteredTransactions.length}건</p>
                </div>
                <div className="bg-white rounded-xl border border-blue-200 p-6 bg-blue-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-blue-700">입금 합계</span><ArrowDownCircle className="w-5 h-5 text-blue-500" /></div>
                    <p className="text-2xl font-bold text-blue-600">{formatCurrency(totalDeposit)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-red-200 p-6 bg-red-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-red-700">출금 합계</span><ArrowUpCircle className="w-5 h-5 text-red-500" /></div>
                    <p className="text-2xl font-bold text-red-600">{formatCurrency(totalWithdrawal)}원</p>
                </div>
            </div>

            {/* 필터 영역 */}
            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
                    <div className="md:col-span-2 relative">
                        <Search className="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                        <input type="text" placeholder="내용, 계좌명 검색..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" />
                    </div>
                    <select value={filterAccount} onChange={(e) => setFilterAccount(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="">전체 계좌</option>
                        {accounts.map(acc => <option key={acc.bankAccountNum} value={acc.bankAccountNum}>{acc.bankName} {acc.bankAccountNum}</option>)}
                    </select>
                    <div className="flex gap-1">
                        {['all', 'deposit', 'withdrawal'].map(type => (
                            <button key={type} onClick={() => setFilterType(type)} className={`flex-1 px-2 py-2 rounded-lg text-xs font-medium ${filterType === type ? (type === 'deposit' ? 'bg-blue-600 text-white' : type === 'withdrawal' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white') : 'bg-gray-100 text-gray-700'}`}>
                                {type === 'all' ? '전체' : getTypeLabel(type)}
                            </button>
                        ))}
                    </div>
                    <button onClick={resetFilters} className="flex items-center justify-center gap-2 px-3 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">
                        <RefreshCw className="w-4 h-4" /><span className="text-sm">초기화</span>
                    </button>
                    <button onClick={fetchTransactions} disabled={loading} className="flex items-center justify-center gap-2 px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50">
                        {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
                        <span className="text-sm">{loading ? '조회 중...' : '조회'}</span>
                    </button>
                </div>
                <div className="flex gap-4 mt-4">
                    <div className="flex items-center gap-2">
                        <span className="text-sm text-gray-500">기간:</span>
                        <input type="date" value={dateRange.start} onChange={(e) => setDateRange(prev => ({ ...prev, start: e.target.value }))} className="px-3 py-2 border border-gray-300 rounded-lg text-sm" />
                        <span className="text-gray-400">~</span>
                        <input type="date" value={dateRange.end} onChange={(e) => setDateRange(prev => ({ ...prev, end: e.target.value }))} className="px-3 py-2 border border-gray-300 rounded-lg text-sm" />
                    </div>
                </div>
            </div>

            {/* 에러 메시지 */}
            {error && (
                <div className="bg-amber-50 border border-amber-200 rounded-xl p-4 mb-6">
                    <p className="text-sm text-amber-700">{error}</p>
                </div>
            )}

            {/* 거래내역 테이블 */}
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                <table className="w-full">
                    <thead className="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">날짜</th>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">계좌</th>
                            <th className="px-6 py-3 text-center text-xs font-semibold text-gray-600">구분</th>
                            <th className="px-6 py-3 text-left text-xs font-semibold text-gray-600">내용</th>
                            <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">금액</th>
                            <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600">잔액</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {loading ? (
                            <tr><td colSpan="6" className="px-6 py-12 text-center text-gray-400">
                                <div className="flex items-center justify-center gap-2">
                                    <svg className="animate-spin h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                                    바로빌에서 데이터를 불러오는 중...
                                </div>
                            </td></tr>
                        ) : filteredTransactions.length === 0 ? (
                            <tr><td colSpan="6" className="px-6 py-12 text-center text-gray-400">거래내역이 없습니다.</td></tr>
                        ) : filteredTransactions.map(item => (
                            <tr key={item.id} className="hover:bg-gray-50">
                                <td className="px-6 py-4">
                                    <p className="text-sm text-gray-600">{item.date}</p>
                                    {item.time && <p className="text-xs text-gray-400">{item.time}</p>}
                                </td>
                                <td className="px-6 py-4">
                                    <p className="text-sm font-medium text-gray-900">{item.accountName}</p>
                                    <p className="text-xs text-gray-400">{item.accountNo}</p>
                                </td>
                                <td className="px-6 py-4 text-center">
                                    <span className="inline-flex items-center gap-1">
                                        {getTypeIcon(item.type)}
                                        <span className={`text-sm font-medium ${getTypeStyle(item.type)}`}>{getTypeLabel(item.type)}</span>
                                    </span>
                                </td>
                                <td className="px-6 py-4">
                                    <p className="text-sm text-gray-900">{item.description}</p>
                                    {item.cast && <p className="text-xs text-gray-400">{item.cast}</p>}
                                    {item.category && <span className="inline-block mt-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-600">{item.category}</span>}
                                </td>
                                <td className={`px-6 py-4 text-sm font-bold text-right ${getTypeStyle(item.type)}`}>
                                    {item.type === 'deposit' ? '+' : '-'}{formatCurrency(item.amount)}원
                                </td>
                                <td className="px-6 py-4 text-sm text-right text-gray-900">{formatCurrency(item.balance)}원</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

const rootElement = document.getElementById('account-transactions-root');
if (rootElement) { ReactDOM.createRoot(rootElement).render(<AccountTransactions />); }
</script>
@endverbatim
@endpush
