@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="subscription-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 RefreshCw = createIcon('refresh-cw');
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 DollarSign = createIcon('dollar-sign');
const Calendar = createIcon('calendar');
const CheckCircle = createIcon('check-circle');
const AlertCircle = createIcon('alert-circle');
const Users = createIcon('users');

function SubscriptionManagement() {
    const [subscriptions, setSubscriptions] = useState([]);
    const [stats, setStats] = useState({ activeCount: 0, monthlyRecurring: 0, yearlyRecurring: 0, totalUsers: 0 });
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

    const [searchTerm, setSearchTerm] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filterPlan, setFilterPlan] = useState('all');

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

    const plans = ['Starter', 'Business', 'Enterprise'];
    const billingCycles = [{ value: 'monthly', label: '월간' }, { value: 'yearly', label: '연간' }];

    const initialFormState = {
        customer: '',
        plan: 'Business',
        monthlyFee: '',
        billingCycle: 'monthly',
        startDate: new Date().toISOString().split('T')[0],
        nextBilling: '',
        status: 'active',
        users: '',
        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 fetchData = async () => {
        setLoading(true);
        try {
            const res = await fetch('/finance/subscriptions/list');
            const data = await res.json();
            if (data.success) {
                setSubscriptions(data.data);
                setStats(data.stats);
            }
        } catch (err) {
            console.error('조회 실패:', err);
        } finally {
            setLoading(false);
        }
    };
    useEffect(() => { fetchData(); }, []);

    const filteredSubscriptions = subscriptions.filter(item => {
        const matchesSearch = (item.customer || '').toLowerCase().includes(searchTerm.toLowerCase());
        const matchesStatus = filterStatus === 'all' || item.status === filterStatus;
        const matchesPlan = filterPlan === 'all' || item.plan === filterPlan;
        return matchesSearch && matchesStatus && matchesPlan;
    });

    const handleAdd = () => { setModalMode('add'); setFormData(initialFormState); setShowModal(true); };
    const handleEdit = (item) => {
        setModalMode('edit');
        setEditingItem(item);
        const safeItem = {};
        Object.keys(initialFormState).forEach(key => { safeItem[key] = item[key] ?? ''; });
        setFormData(safeItem);
        setShowModal(true);
    };
    const handleSave = async () => {
        if (!formData.customer || !formData.monthlyFee) { alert('필수 항목을 입력해주세요.'); return; }
        setSaving(true);
        try {
            const url = modalMode === 'add' ? '/finance/subscriptions/store' : `/finance/subscriptions/${editingItem.id}`;
            const body = { ...formData, monthlyFee: parseInt(formData.monthlyFee) || 0, users: parseInt(formData.users) || 0 };
            const res = await fetch(url, {
                method: modalMode === 'add' ? 'POST' : 'PUT',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken },
                body: JSON.stringify(body),
            });
            const data = await res.json();
            if (!res.ok) {
                const errors = data.errors ? Object.values(data.errors).flat().join('\n') : data.message;
                alert(errors || '저장에 실패했습니다.');
                return;
            }
            setShowModal(false);
            setEditingItem(null);
            fetchData();
        } catch (err) {
            console.error('저장 실패:', err);
            alert('저장에 실패했습니다.');
        } finally {
            setSaving(false);
        }
    };
    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;
        try {
            const res = await fetch(`/finance/subscriptions/${id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken },
            });
            if (res.ok) {
                setShowModal(false);
                fetchData();
            }
        } catch (err) {
            console.error('삭제 실패:', err);
            alert('삭제에 실패했습니다.');
        }
    };

    const handleDownload = () => {
        const rows = [['구독관리'], [], ['고객사', '플랜', '월 요금', '결제주기', '시작일', '다음결제', '상태', '사용자수'],
            ...filteredSubscriptions.map(item => [item.customer, item.plan, item.monthlyFee, item.billingCycle === 'monthly' ? '월간' : '연간', item.startDate, item.nextBilling, item.status, item.users])];
        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 = '구독관리.csv'; link.click();
    };

    const getStatusColor = (status) => {
        const colors = { active: 'bg-emerald-100 text-emerald-700', trial: 'bg-blue-100 text-blue-700', cancelled: 'bg-rose-100 text-rose-700', paused: 'bg-amber-100 text-amber-700' };
        return colors[status] || 'bg-gray-100 text-gray-700';
    };
    const getStatusLabel = (status) => {
        const labels = { active: '활성', trial: '체험', cancelled: '해지', paused: '일시정지' };
        return labels[status] || status;
    };
    const getPlanColor = (plan) => {
        const colors = { Starter: 'bg-gray-100 text-gray-700', Business: 'bg-blue-100 text-blue-700', Enterprise: 'bg-purple-100 text-purple-700' };
        return colors[plan] || 'bg-gray-100 text-gray-700';
    };

    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-teal-100 rounded-xl"><RefreshCw className="w-6 h-6 text-teal-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">구독관리</h1><p className="text-sm text-gray-500">Subscription Management</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><CheckCircle className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{stats.activeCount}개</p>
                </div>
                <div className="bg-white rounded-xl border border-teal-200 p-6 bg-teal-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-teal-700">월 반복 수익(MRR)</span><DollarSign className="w-5 h-5 text-teal-500" /></div>
                    <p className="text-2xl font-bold text-teal-600">{formatCurrency(stats.monthlyRecurring)}원</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">연 반복 수익(ARR)</span></div>
                    <p className="text-2xl font-bold text-emerald-600">{formatCurrency(stats.yearlyRecurring)}원</p>
                </div>
                <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><Users className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{stats.totalUsers}명</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-4 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-teal-500" />
                    </div>
                    <select value={filterPlan} onChange={(e) => setFilterPlan(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg"><option value="all">전체 플랜</option>{plans.map(p => <option key={p} value={p}>{p}</option>)}</select>
                    <div className="flex gap-1">
                        {['all', 'active', 'trial', 'cancelled'].map(status => (
                            <button key={status} onClick={() => setFilterStatus(status)} className={`flex-1 px-2 py-2 rounded-lg text-xs font-medium ${filterStatus === status ? (status === 'active' ? 'bg-green-600 text-white' : status === 'trial' ? 'bg-blue-600 text-white' : status === 'cancelled' ? 'bg-red-600 text-white' : 'bg-gray-800 text-white') : 'bg-gray-100 text-gray-700'}`}>
                                {status === 'all' ? '전체' : getStatusLabel(status)}
                            </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-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>
                            <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>
                            <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">
                        {loading ? (
                            <tr><td colSpan="8" 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>
                        ) : filteredSubscriptions.length === 0 ? (
                            <tr><td colSpan="8" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
                        ) : filteredSubscriptions.map(item => (
                            <tr key={item.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => handleEdit(item)}>
                                <td className="px-6 py-4"><p className="text-sm font-medium text-gray-900">{item.customer}</p>{item.memo && <p className="text-xs text-gray-400">{item.memo}</p>}</td>
                                <td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getPlanColor(item.plan)}`}>{item.plan}</span></td>
                                <td className="px-6 py-4 text-sm font-bold text-right text-teal-600">{formatCurrency(item.monthlyFee)}원</td>
                                <td className="px-6 py-4 text-sm text-center text-gray-600">{item.billingCycle === 'monthly' ? '월간' : '연간'}</td>
                                <td className="px-6 py-4 text-sm text-center text-gray-600">{item.nextBilling}</td>
                                <td className="px-6 py-4 text-sm text-center text-gray-600">{item.users}명</td>
                                <td className="px-6 py-4 text-center"><span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(item.status)}`}>{getStatusLabel(item.status)}</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><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 className="grid grid-cols-2 gap-4">
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">플랜</label><select value={formData.plan} onChange={(e) => setFormData(prev => ({ ...prev, plan: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{plans.map(p => <option key={p} value={p}>{p}</option>)}</select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">월 요금 *</label><input type="text" value={formatInputCurrency(formData.monthlyFee)} onChange={(e) => setFormData(prev => ({ ...prev, monthlyFee: parseInputCurrency(e.target.value) }))} placeholder="0" 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.billingCycle} onChange={(e) => setFormData(prev => ({ ...prev, billingCycle: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{billingCycles.map(b => <option key={b.value} value={b.value}>{b.label}</option>)}</select></div>
                                <div><label className="block text-sm font-medium text-gray-700 mb-1">사용자 수</label><input type="number" value={formData.users} onChange={(e) => setFormData(prev => ({ ...prev, users: e.target.value }))} placeholder="0" 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><input type="date" value={formData.startDate} onChange={(e) => setFormData(prev => ({ ...prev, startDate: 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><input type="date" value={formData.nextBilling} onChange={(e) => setFormData(prev => ({ ...prev, nextBilling: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg" /></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="active">활성</option><option value="trial">체험</option><option value="paused">일시정지</option><option value="cancelled">해지</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} disabled={saving} className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg disabled:opacity-50 disabled:cursor-not-allowed">{saving ? '저장 중...' : (modalMode === 'add' ? '등록' : '저장')}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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