@extends('layouts.app')

@section('title', '차량정비이력')

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

@section('content')
<div id="vehicle-maintenance-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 Wrench = createIcon('wrench');
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 Fuel = createIcon('fuel');
const Car = createIcon('car');
const RotateCw = createIcon('rotate-cw');

function VehicleMaintenanceManagement() {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    // 차량 목록 (API에서 로드)
    const [vehicles, setVehicles] = useState([]);

    // 정비 이력 (API에서 로드)
    const [maintenances, setMaintenances] = useState([]);

    // 데이터 로드
    const loadVehicles = async () => {
        try {
            const response = await fetch('/finance/vehicle-maintenance/vehicles');
            const result = await response.json();
            if (result.success) {
                setVehicles(result.data.map(v => ({
                    id: v.id,
                    plateNumber: v.plate_number,
                    model: v.model,
                    ownershipType: v.ownership_type,
                    currentMileage: v.mileage || 0
                })));
            }
        } catch (error) {
            console.error('차량 로드 실패:', error);
        }
    };

    const loadMaintenances = async () => {
        setLoading(true);
        try {
            const params = new URLSearchParams({
                start_date: dateRange.start,
                end_date: dateRange.end,
                category: filterCategory,
                vehicle_id: filterVehicle,
                search: searchTerm
            });
            const response = await fetch(`/finance/vehicle-maintenance/list?${params}`);
            const result = await response.json();
            if (result.success) {
                setMaintenances(result.data);
            }
        } catch (error) {
            console.error('정비 이력 로드 실패:', error);
        } finally {
            setLoading(false);
        }
    };

    // 초기 로드
    useEffect(() => {
        loadVehicles().then(() => loadMaintenances());
    }, []);

    const [searchTerm, setSearchTerm] = useState('');
    const [filterCategory, setFilterCategory] = useState('all');
    const [filterVehicle, setFilterVehicle] = 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 categories = ['주유', '정비', '보험', '세차', '주차', '통행료', '검사', '기타'];

    // 검색 실행
    const handleSearch = () => {
        loadMaintenances();
    };

    // 엔터키 핸들러
    const handleKeyDown = (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    };

    // 차량 표시용 헬퍼
    const getVehicleDisplay = (vehicleId) => {
        const v = vehicles.find(v => v.id === vehicleId);
        return v ? `${v.plateNumber} (${v.model})` : '-';
    };

    const initialFormState = {
        date: new Date().toISOString().split('T')[0],
        vehicleId: vehicles[0]?.id || '',
        category: '주유',
        description: '',
        amount: '',
        mileage: '',
        vendor: '',
        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 totalAmount = maintenances.reduce((sum, item) => sum + item.amount, 0);
    const fuelAmount = maintenances.filter(m => m.category === '주유').reduce((sum, item) => sum + item.amount, 0);
    const maintenanceAmount = maintenances.filter(m => m.category === '정비').reduce((sum, item) => sum + item.amount, 0);
    const otherAmount = totalAmount - fuelAmount - maintenanceAmount;

    // 유지비 등록/수정
    const handleAdd = () => { setModalMode('add'); setFormData({...initialFormState, vehicleId: vehicles[0]?.id || ''}); setShowModal(true); };
    const handleEdit = (item) => {
        setModalMode('edit');
        setEditingItem(item);
        setFormData({
            date: item.date || new Date().toISOString().split('T')[0],
            vehicleId: item.vehicleId || '',
            category: item.category || '주유',
            description: item.description || '',
            amount: item.amount || '',
            mileage: item.mileage || '',
            vendor: item.vendor || '',
            memo: item.memo || ''
        });
        setShowModal(true);
    };
    const handleSave = async () => {
        if (!formData.description) { alert('내용을 입력해주세요.'); return; }
        if (!formData.amount || formData.amount === '0') { alert('금액을 입력해주세요.'); return; }
        if (!formData.vehicleId) { alert('차량을 선택해주세요.'); return; }
        setSaving(true);
        try {
            const payload = {
                vehicle_id: parseInt(formData.vehicleId),
                date: formData.date,
                category: formData.category,
                description: formData.description,
                amount: parseInt(String(formData.amount).replace(/[^\d]/g, '')) || 0,
                mileage: parseInt(String(formData.mileage).replace(/[^\d]/g, '')) || null,
                vendor: formData.vendor,
                memo: formData.memo
            };
            const url = modalMode === 'add' ? '/finance/vehicle-maintenance' : `/finance/vehicle-maintenance/${editingItem.id}`;
            const method = modalMode === 'add' ? 'POST' : 'PUT';
            const response = await fetch(url, {
                method,
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
                body: JSON.stringify(payload)
            });
            const result = await response.json();
            if (result.success) {
                await loadMaintenances();
                setShowModal(false);
                setEditingItem(null);
            } else {
                alert(result.message || '저장에 실패했습니다.');
            }
        } catch (error) {
            console.error('저장 오류:', error);
            alert('저장 중 오류가 발생했습니다: ' + error.message);
        } finally {
            setSaving(false);
        }
    };
    const handleDelete = async (id) => {
        if (!confirm('정말 삭제하시겠습니까?')) return;
        try {
            const response = await fetch(`/finance/vehicle-maintenance/${id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content }
            });
            const result = await response.json();
            if (result.success) {
                await loadMaintenances();
                setShowModal(false);
            } else {
                alert(result.message || '삭제에 실패했습니다.');
            }
        } catch (error) {
            console.error('삭제 오류:', error);
            alert('삭제 중 오류가 발생했습니다.');
        }
    };

    const handleCopy = () => {
        setModalMode('add');
        setEditingItem(null);
        setFormData(prev => ({ ...prev, date: new Date().toISOString().split('T')[0] }));
    };

    const handleDownload = () => {
        const rows = [['차량 유지비', `${dateRange.start} ~ ${dateRange.end}`], [], ['날짜', '차량', '구분', '내용', '금액', '주행거리', '업체'],
            ...maintenances.map(item => [item.date, getVehicleDisplay(item.vehicleId), item.category, item.description, item.amount, item.mileage, item.vendor])];
        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 getCategoryColor = (cat) => {
        const colors = { '주유': 'bg-amber-100 text-amber-700', '정비': 'bg-blue-100 text-blue-700', '보험': 'bg-purple-100 text-purple-700', '세차': 'bg-cyan-100 text-cyan-700', '주차': 'bg-gray-100 text-gray-700', '통행료': 'bg-emerald-100 text-emerald-700', '검사': 'bg-indigo-100 text-indigo-700', '기타': 'bg-slate-100 text-slate-700' };
        return colors[cat] || '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-amber-100 rounded-xl"><Wrench className="w-6 h-6 text-amber-600" /></div>
                        <div><h1 className="text-xl font-bold text-gray-900">차량정비이력</h1><p className="text-sm text-gray-500">Vehicle Maintenance History</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><DollarSign className="w-5 h-5 text-gray-400" /></div>
                    <p className="text-2xl font-bold text-gray-900">{formatCurrency(totalAmount)}원</p>
                    <p className="text-xs text-gray-400 mt-1">{maintenances.length}건</p>
                </div>
                <div className="bg-white rounded-xl border border-amber-200 p-6 bg-amber-50/30">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-amber-700">주유비</span><Fuel className="w-5 h-5 text-amber-500" /></div>
                    <p className="text-2xl font-bold text-amber-600">{formatCurrency(fuelAmount)}원</p>
                </div>
                <div className="bg-white rounded-xl border border-blue-200 p-6">
                    <div className="flex items-center justify-between mb-2"><span className="text-sm text-blue-700">정비비</span><Wrench className="w-5 h-5 text-blue-500" /></div>
                    <p className="text-2xl font-bold text-blue-600">{formatCurrency(maintenanceAmount)}원</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></div>
                    <p className="text-2xl font-bold text-gray-900">{formatCurrency(otherAmount)}원</p>
                </div>
            </div>

            {/* 필터 */}
            <div className="bg-white rounded-xl border border-gray-200 p-4 mb-6">
                <div className="flex flex-wrap items-center gap-3">
                    <div className="relative flex-1 min-w-[200px]">
                        <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)}
                            onKeyDown={handleKeyDown}
                            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500"
                        />
                    </div>
                    <select value={filterVehicle} onChange={(e) => setFilterVehicle(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 차량</option>
                        {vehicles.map(v => <option key={v.id} value={v.id}>{v.plateNumber} ({v.model})</option>)}
                    </select>
                    <select value={filterCategory} onChange={(e) => setFilterCategory(e.target.value)} className="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="all">전체 구분</option>
                        {categories.map(c => <option key={c} value={c}>{c}</option>)}
                    </select>
                    <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" />
                    <button
                        onClick={handleSearch}
                        disabled={loading}
                        className="flex items-center gap-2 px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white rounded-lg disabled:opacity-50"
                    >
                        <Search className="w-4 h-4" />
                        <span className="text-sm font-medium">검색</span>
                    </button>
                    <button
                        onClick={handleSearch}
                        disabled={loading}
                        className="flex items-center gap-2 px-3 py-2 border border-gray-300 text-gray-700 hover:bg-gray-100 rounded-lg disabled:opacity-50"
                        title="새로고침"
                    >
                        <svg className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                    </button>
                </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-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>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100">
                        {loading ? (
                            <tr><td colSpan="7" className="px-6 py-12 text-center text-gray-400">로딩 중...</td></tr>
                        ) : maintenances.length === 0 ? (
                            <tr><td colSpan="7" className="px-6 py-12 text-center text-gray-400">데이터가 없습니다.</td></tr>
                        ) : maintenances.map(item => {
                            const vehicle = vehicles.find(v => v.id === item.vehicleId);
                            return (
                                <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">
                                        <p className="text-sm font-medium text-gray-900">{vehicle?.plateNumber || '-'}</p>
                                        <p className="text-xs text-gray-400">{vehicle?.model || ''}</p>
                                    </td>
                                    <td className="px-6 py-4"><span className={`px-2 py-1 rounded text-xs font-medium ${getCategoryColor(item.category)}`}>{item.category}</span></td>
                                    <td className="px-6 py-4"><p className="text-sm text-gray-900">{item.description}</p>{item.vendor && <p className="text-xs text-gray-400">{item.vendor}</p>}</td>
                                    <td className="px-6 py-4 text-sm font-bold text-right text-amber-600">{formatCurrency(item.amount)}원</td>
                                    <td className="px-6 py-4 text-sm text-right text-gray-600">{formatCurrency(item.mileage)}km</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.category} onChange={(e) => setFormData(prev => ({ ...prev, category: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">{categories.map(c => <option key={c} value={c}>{c}</option>)}</select></div>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">차량</label>
                                <select value={formData.vehicleId} onChange={(e) => setFormData(prev => ({ ...prev, vehicleId: e.target.value }))} className="w-full px-3 py-2 border border-gray-300 rounded-lg">
                                    {vehicles.map(v => <option key={v.id} value={v.id}>{v.plateNumber} ({v.model})</option>)}
                                </select>
                            </div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">내용 *</label><input type="text" value={formData.description} onChange={(e) => setFormData(prev => ({ ...prev, description: 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><input type="text" value={formatInputCurrency(formData.amount)} onChange={(e) => setFormData(prev => ({ ...prev, amount: 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">주행거리(km)</label><input type="text" value={formatInputCurrency(formData.mileage)} onChange={(e) => setFormData(prev => ({ ...prev, mileage: 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><input type="text" value={formData.vendor} onChange={(e) => setFormData(prev => ({ ...prev, vendor: 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.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">삭제</button>}
                            {modalMode === 'edit' && <button onClick={handleCopy} className="px-4 py-2 border border-teal-500 text-teal-600 rounded-lg hover:bg-teal-50">복사</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">{saving ? '저장 중...' : (modalMode === 'add' ? '등록' : '저장')}</button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}

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