@extends('layouts.app')

@section('title', '영업수수료')

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

@section('content')
<div id="sales-commission-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, 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 DollarSign = createIcon('dollar-sign');
const Plus = createIcon('plus');
const Search = createIcon('search');
const Download = createIcon('download');
const X = createIcon('x');
const Edit = createIcon('edit');
const Trash2 = createIcon('trash-2');
const Users = createIcon('users');
const Percent = createIcon('percent');
const TrendingUp = createIcon('trending-up');

function SalesCommissionManagement() {
    const [commissions, setCommissions] = useState([
        { id: 1, date: '2026-01-21', salesperson: '박영업', customer: '(주)제조산업', project: 'MES 시스템', salesAmount: 160000000, rate: 3, commission: 4800000, status: 'pending', memo: '계약 성사' },
        { id: 2, date: '2026-01-15', salesperson: '김세일', customer: '(주)테크솔루션', project: 'SaaS 구독', salesAmount: 6000000, rate: 5, commission: 300000, status: 'paid', memo: '신규 고객' },
        { id: 3, date: '2026-01-10', salesperson: '박영업', customer: '(주)디지털제조', project: 'ERP 연동', salesAmount: 80000000, rate: 3, commission: 2400000, status: 'paid', memo: '' },
        { id: 4, date: '2026-01-05', salesperson: '이영업', customer: '(주)AI산업', project: '유지보수', salesAmount: 36000000, rate: 2, commission: 720000, status: 'pending', memo: '연장 계약' },
        { id: 5, date: '2025-12-20', salesperson: '김세일', customer: '(주)스마트팩토리', project: '컨설팅', salesAmount: 15000000, rate: 5, commission: 750000, status: 'paid', memo: '' },
    ]);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filterPerson, setFilterPerson] = useState('all');
    const [dateRange, setDateRange] = useState({
        start: new Date(new Date().setMonth(new Date().getMonth() - 3)).toISOString().split('T')[0],
        end: new Date().toISOString().split('T')[0]
    });

    const [showModal, setShowModal] = useState(false);
    const [modalMode, setModalMode] = useState('add');
    const [editingItem, setEditingItem] = useState(null);

    const salespersons = ['박영업', '김세일', '이영업', '최판매'];

    const initialFormState = {
        date: new Date().toISOString().split('T')[0],
        salesperson: '박영업',
        customer: '',
        project: '',
        salesAmount: '',
        rate: 3,
        commission: '',
        status: 'pending',
        memo: ''
    };
    const [formData, setFormData] = useState(initialFormState);

    const formatCurrency = (num) => num ? num.toLocaleString() : '0';
    const formatInputCurrency = (value) => {
        if (!value && value !== 0) return '';
        const num = String(value).replace(/[^\d]/g, '');
        return num ? Number(num).toLocaleString() : '';
    };
    const parseInputCurrency = (value) => String(value).replace(/[^\d]/g, '');

    const filteredCommissions = commissions.filter(item => {
        const matchesSearch = item.customer.toLowerCase().includes(searchTerm.toLowerCase()) ||
                             item.project.toLowerCase().includes(searchTerm.toLowerCase()) ||
                             item.salesperson.toLowerCase().includes(searchTerm.toLowerCase());
        const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
        const matchesPerson = filterPerson === 'all' || item.salesperson === filterPerson;
        const matchesDate = item.date >= dateRange.start && item.date <= dateRange.end;
        return matchesSearch && matchesStatus && matchesPerson && matchesDate;
    });

    const totalCommission = filteredCommissions.reduce((sum, item) => sum + item.commission, 0);
    const paidCommission = filteredCommissions.filter(i => i.status === 'paid').reduce((sum, item) => sum + item.commission, 0);
    const pendingCommission = filteredCommissions.filter(i => i.status === 'pending').reduce((sum, item) => sum + item.commission, 0);
    const totalSales = filteredCommissions.reduce((sum, item) => sum + item.salesAmount, 0);

    const handleAdd = () => { setModalMode('add'); setFormData(initialFormState); setShowModal(true); };
    const handleEdit = (item) => { setModalMode('edit'); setEditingItem(item); setFormData({ ...item }); setShowModal(true); };
    const handleSave = () => {
        if (!formData.customer || !formData.salesAmount) { alert('필수 항목을 입력해주세요.'); return; }
        const salesAmount = parseInt(formData.salesAmount) || 0;
        const commission = parseInt(formData.commission) || Math.round(salesAmount * (formData.rate / 100));
        if (modalMode === 'add') {
            setCommissions(prev => [{ id: Date.now(), ...formData, salesAmount, commission }, ...prev]);
        } else {
            setCommissions(prev => prev.map(item => item.id === editingItem.id ? { ...item, ...formData, salesAmount, commission } : item));
        }
        setShowModal(false); setEditingItem(null);
    };
    const handleDelete = (id) => { if (confirm('정말 삭제하시겠습니까?')) { setCommissions(prev => prev.filter(item => item.id !== id)); setShowModal(false); } };

    const handleDownload = () => {
        const rows = [['영업수수료', `${dateRange.start} ~ ${dateRange.end}`], [], ['날짜', '영업파트너', '고객사', '프로젝트', '매출액', '수수료율', '수수료', '상태'],
            ...filteredCommissions.map(item => [item.date, item.salesperson, item.customer, item.project, item.salesAmount, `${item.rate}%`, item.commission, item.status === 'paid' ? '지급완료' : '지급예정'])];
        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();
    };

    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-violet-100 rounded-xl"><DollarSign className="w-6 h-6 text-violet-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">영업수수료</h1><p className="text-sm text-gray-500">Sales Commission</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>
                        <button onClick={handleAdd} className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg"><Plus className="w-4 h-4" /><span className="text-sm font-medium">수수료 등록</span></button>
                    </div>
                </div>
            </header>

            <div className="grid grid-cols-1 md:grid-cols-4 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><TrendingUp className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{formatCurrency(totalSales)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-violet-200 p-6 bg-violet-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-violet-700">총 수수료</span><DollarSign className="w-5 h-5 text-violet-500" /></div>
                    <p className="text-2xl font-bold text-violet-600">{formatCurrency(totalCommission)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-emerald-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-emerald-700">지급완료</span></div>
                    <p className="text-2xl font-bold text-emerald-600">{formatCurrency(paidCommission)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-amber-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-amber-700">지급예정</span></div>
                    <p className="text-2xl font-bold text-amber-600">{formatCurrency(pendingCommission)}원</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-5 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-violet-500" />
                    </div>
                    <select value={filterPerson} onChange={(e) => setFilterPerson(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg"><option value="all">전체 담당자</option>{salespersons.map(p => <option key={p} value={p}>{p}</option>)}</select>
                    <div className="flex items-center gap-2">
                        <input type="date" value={dateRange.start} onChange={(e) => setDateRange(prev => ({ ...prev, start: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
                        <span>~</span>
                        <input type="date" value={dateRange.end} onChange={(e) => setDateRange(prev => ({ ...prev, end: e.target.value }))} className="flex-1 px-2 py-2 border border-gray-300 rounded-lg text-sm" />
                    </div>
                    <div className="flex gap-1">
                        {['all', 'paid', 'pending'].map(status => (
                            <button key={status} onClick={() => setFilterStatus(status)} className={`flex-1 px-3 py-2 rounded-lg text-sm font-medium ${filterStatus === status ? (status === 'paid' ? 'bg-green-600 text-white' : status === 'pending' ? 'bg-yellow-500 text-white' : 'bg-gray-800 text-white') : 'bg-gray-100 text-gray-700'}`}>
                                {status === 'all' ? '전체' : status === 'paid' ? '완료' : '예정'}
                            </button>
                        ))}
                    </div>
                </div>
            </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-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-right 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-right 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-center text-xs font-semibold text-gray-600">관리</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {filteredCommissions.length === 0 ? (
                            <tr><td colSpan="9" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
                        ) : filteredCommissions.map(item => (
                            <tr key={item.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleEdit(item)}>
                                <td className="px-6 py-4 text-sm text-gray-600">{item.date}</td>
                                <td className="px-6 py-4"><span className="px-2 py-1 bg-violet-100 text-violet-700 rounded text-xs font-medium">{item.salesperson}</span></td>
                                <td className="px-6 py-4 text-sm font-medium text-gray-900">{item.customer}</td>
                                <td className="px-6 py-4 text-sm text-gray-600">{item.project}</td>
                                <td className="px-6 py-4 text-sm text-right text-gray-900">{formatCurrency(item.salesAmount)}원</td>
                                <td className="px-6 py-4 text-sm text-center text-gray-600">{item.rate}%</td>
                                <td className="px-6 py-4 text-sm font-bold text-right text-violet-600">{formatCurrency(item.commission)}원</td>
                                <td className="px-6 py-4 text-center"><span className={`px-2 py-1 rounded-full text-xs font-medium ${item.status === 'paid' ? 'bg-emerald-100 text-emerald-700' : 'bg-amber-100 text-amber-700'}`}>{item.status === 'paid' ? '지급완료' : '지급예정'}</span></td>
                                <td className="px-6 py-4 text-center" onClick={(e) => e.stopPropagation()}>
                                    <button onClick={() => handleEdit(item)} className="p-1 text-gray-400 hover:text-blue-500"><Edit className="w-4 h-4" /></button>
                                    <button onClick={() => handleDelete(item.id)} className="p-1 text-gray-400 hover:text-rose-500"><Trash2 className="w-4 h-4" /></button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

            {showModal && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-xl p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
                        <div className="flex items-center justify-between mb-6">
                            <h3 className="text-lg font-bold text-gray-900">{modalMode === 'add' ? '수수료 등록' : '수수료 수정'}</h3>
                            <button onClick={() => setShowModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X className="w-5 h-5 text-gray-500" /></button>
                        </div>
                        <div className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">날짜 *</label><input type="date" value={formData.date} onChange={(e) => setFormData(prev => ({ ...prev, date: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">영업파트너</label><select value={formData.salesperson} onChange={(e) => setFormData(prev => ({ ...prev, salesperson: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{salespersons.map(p => <option key={p} value={p}>{p}</option>)}</select></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">고객사 *</label><input type="text" value={formData.customer} onChange={(e) => setFormData(prev => ({ ...prev, customer: e.target.value }))} placeholder="고객사명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">프로젝트</label><input type="text" value={formData.project} onChange={(e) => setFormData(prev => ({ ...prev, project: e.target.value }))} placeholder="프로젝트명" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            <div className="grid grid-cols-3 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">매출액 *</label><input type="text" value={formatInputCurrency(formData.salesAmount)} onChange={(e) => setFormData(prev => ({ ...prev, salesAmount: parseInputCurrency(e.target.value) }))} placeholder="0" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">수수료율(%)</label><input type="number" value={formData.rate} onChange={(e) => setFormData(prev => ({ ...prev, rate: parseFloat(e.target.value) || 0 }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">수수료</label><input type="text" value={formatInputCurrency(formData.commission)} onChange={(e) => setFormData(prev => ({ ...prev, commission: parseInputCurrency(e.target.value) }))} placeholder="자동계산" className="w-full px-3 py-2 border border-gray-300 rounded-lg text-right" /></div>
                            </div>
                            <div className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">상태</label><select value={formData.status} onChange={(e) => setFormData(prev => ({ ...prev, status: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg"><option value="pending">지급예정</option><option value="paid">지급완료</option></select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">메모</label><input type="text" value={formData.memo} onChange={(e) => setFormData(prev => ({ ...prev, memo: e.target.value }))} placeholder="메모" className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></div>
                            </div>
                        </div>
                        <div className="flex gap-3 mt-6">
                            {modalMode === 'edit' && <button onClick={() => handleDelete(editingItem.id)} className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg flex items-center gap-2"><span>🗑️</span> 삭제</button>}
                            <button onClick={() => setShowModal(false)} className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">취소</button>
                            <button onClick={handleSave} className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg">{modalMode === 'add' ? '등록' : '저장'}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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