const { useState, useEffect, useCallback } = React;

// ─── Durum Renkleri ─────────────────────────────────────────────────────────
const STATUS_MAP = {
    pending: { label: 'Bekliyor', color: '#f59e0b', bg: 'rgba(245,158,11,0.1)' },
    confirmed: { label: 'Onaylandi', color: '#3b82f6', bg: 'rgba(59,130,246,0.1)' },
    calling: { label: 'Araniyor', color: '#8b5cf6', bg: 'rgba(139,92,246,0.1)' },
    completed: { label: 'Tamamlandi', color: '#22c55e', bg: 'rgba(34,197,94,0.1)' },
    cancelled: { label: 'Iptal', color: '#94a3b8', bg: 'rgba(148,163,184,0.1)' },
    missed: { label: 'Kacirildi', color: '#ef4444', bg: 'rgba(239,68,68,0.1)' },
};

function StatusBadge({ status }) {
    const s = STATUS_MAP[status] || STATUS_MAP.pending;
    return (
        <span style={{
            fontSize: 11, fontWeight:600, padding: '3px 10px', borderRadius: 99,
            background: s.bg, color: s.color, border: `1px solid ${s.color}22`,
            whiteSpace: 'nowrap'
        }}>
            {s.label}
        </span>
    );
}

// ─── Tarih formatlama ─────────────────────────────────────────────────────────
// Backend datetime'ları parseUTC ile yorumlanır (Z suffix yoksa UTC kabul edilir).
function fmtDate(iso) {
    const d = parseUTC(iso);
    if (!d) return '-';
    const pad = n =>String(n).padStart(2, '0');
    return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function timeUntil(iso) {
    const target = parseUTC(iso);
    if (!target) return '';
    const diff = target.getTime() - Date.now();
    if (diff < 0) return 'Gecmis';
    const h = Math.floor(diff / 3600000);
    const m = Math.floor((diff % 3600000) / 60000);
    if (h > 24) return `${Math.floor(h / 24)} gun`;
    if (h > 0) return `${h}sa ${m}dk`;
    return `${m}dk`;
}

// ─── Yeni Randevu Modal ─────────────────────────────────────────────────────
function NewAppointmentModal({ onClose, onSave }) {
    const [form, setForm] = useState({
        phone: '', customer_name: '', subject: '', notes: '',
        appointment_date: '', auto_callback: true, max_retries: 2
    });
    const set = (k, v) =>setForm(f => ({ ...f, [k]: v }));

    async function save() {
        if (!form.phone || !form.appointment_date) return;
        const body = {
            ...form,
            appointment_date: new Date(form.appointment_date).toISOString(),
        };
        const r = await authFetch('/api/appointments', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        if (r.ok) onSave();
    }

    return (
        <div className="overlay" onClick={onClose}>
            <div className="modal" onClick={e =>e.stopPropagation()} style={{ maxWidth: 500 }}>
                <div className="modal-header">
                    <span style={{ fontWeight:600, fontSize: 18 }}>Yeni Randevu</span>
                    <button className="close-btn" onClick={onClose}>&times;</button>
                </div>
                <div className="modal-body">
                    <div className="form-group">
                        <label className="form-label">Telefon Numarasi *</label>
                        <input className="form-input" value={form.phone} onChange={e =>set('phone', e.target.value)} placeholder="05XX XXX XX XX" />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Musteri Adi</label>
                        <input className="form-input" value={form.customer_name} onChange={e =>set('customer_name', e.target.value)} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Randevu Tarihi ve Saati *</label>
                        <input className="form-input" type="datetime-local" value={form.appointment_date} onChange={e =>set('appointment_date', e.target.value)} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Konu</label>
                        <input className="form-input" value={form.subject} onChange={e =>set('subject', e.target.value)} placeholder="Randevu nedeni" />
                    </div>
                    <div className="form-group">
                        <label className="form-label">Notlar</label>
                        <textarea className="form-textarea" rows={3} value={form.notes} onChange={e =>set('notes', e.target.value)} />
                    </div>
                    <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
                        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
                            <input type="checkbox" checked={form.auto_callback} onChange={e =>set('auto_callback', e.target.checked)} style={{ accentColor: 'var(--blue)' }} />
                            <span style={{ fontSize: 13 }}>Otomatik geri arama</span>
                        </label>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <span style={{ fontSize: 13 }}>Max deneme:</span>
                            <input type="number" min={0} max={5} value={form.max_retries} onChange={e =>set('max_retries', +e.target.value)} style={{ width: 50, padding: '4px 8px', borderRadius: 6, border: '1px solid var(--border)', background: 'var(--surface2)', color: 'var(--text)', fontSize: 13 }} />
                        </div>
                    </div>
                </div>
                <div className="modal-footer">
                    <button className="btn outline" onClick={onClose}>Iptal</button>
                    <button className="btn primary" onClick={save} disabled={!form.phone || !form.appointment_date}>Randevu Olustur</button>
                </div>
            </div>
        </div>
    );
}

// ─── Ana Randevular Tab ─────────────────────────────────────────────────────
function AppointmentsTab({ toast }) {
    const [appointments, setAppointments] = useState([]);
    const [stats, setStats] = useState(null);
    const [filterStatus, setFilterStatus] = useState('');
    const [filterDate, setFilterDate] = useState('');
    const [modal, setModal] = useState(false);
    const [loading, setLoading] = useState(false);

    const load = useCallback(async () => {
        setLoading(true);
        try {
            let url = '/api/appointments?limit=200';
            if (filterStatus) url += `&status=${filterStatus}`;
            if (filterDate) url += `&date_from=${filterDate}T00:00:00&date_to=${filterDate}T23:59:59`;
            const r = await authFetch(url);
            if (r.ok) setAppointments(await r.json());

            const sr = await authFetch('/api/appointments/stats');
            if (sr.ok) setStats(await sr.json());
        } finally { setLoading(false); }
    }, [filterStatus, filterDate]);

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

    async function cancelAppt(id) {
        if (!confirm('Randevuyu iptal etmek istediginize emin misiniz?')) return;
        const r = await authFetch(`/api/appointments/${id}/cancel`, { method: 'POST' });
        if (r.ok) { toast('Randevu iptal edildi', 'success'); load(); }
        else toast('Iptal basarisiz', 'error');
    }

    async function callAppt(id) {
        if (!confirm('Bu randevu icin simdi geri arama baslatilsin mi?')) return;
        const r = await authFetch(`/api/appointments/${id}/call`, { method: 'POST' });
        if (r.ok) { toast('Geri arama baslatildi', 'success'); load(); }
        else toast('Geri arama basarisiz', 'error');
    }

    async function deleteAppt(id) {
        if (!confirm('Randevuyu silmek istediginize emin misiniz?')) return;
        const r = await authFetch(`/api/appointments/${id}`, { method: 'DELETE' });
        if (r.ok) { toast('Randevu silindi', 'success'); load(); }
    }

    // ── Stat Kartı
    const StatCard = ({ label, value, color }) => (
        <div style={{
            flex: '1 1 120px', padding: '16px 20px', borderRadius: 12,
            background: 'var(--surface)', border: '1px solid var(--border)',
            textAlign: 'center'
        }}>
            <div className="mono" style={{ fontSize: 28, fontWeight:600, color: color || 'var(--text)' }}>{value}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', fontWeight: 600, marginTop: 4 }}>{label}</div>
        </div>
    );

    return (
        <div className="fade-in">
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                <div>
                    <h2 style={{ fontSize: 24, fontWeight:600, color: 'var(--text)' }}>Randevu Yonetimi</h2>
                    <p style={{ fontSize: 14, color: 'var(--text-dim)', marginTop: 6 }}>
                        AI asistanin aldigi ve manuel olusturulan randevular. Otomatik geri arama destegi.
                    </p>
                </div>
                <button className="btn primary" onClick={() =>setModal(true)}>+ Yeni Randevu</button>
            </div>

            {/* Stat Kartlari */}
            {stats && (
                <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap' }}>
                    <StatCard label="Toplam" value={stats.total} />
                    <StatCard label="Bekliyor" value={stats.pending} color="var(--amber)" />
                    <StatCard label="Bugun" value={stats.today} color="var(--blue)" />
                    <StatCard label="Yarin" value={stats.tomorrow} color="var(--purple, #7c3aed)" />
                    <StatCard label="Tamamlandi" value={stats.completed} color="var(--green)" />
                    <StatCard label="Kacirildi" value={stats.missed} color="var(--red)" />
                </div>
            )}

            {/* Yaklaşan Randevular */}
            {stats && stats.upcoming && stats.upcoming.length > 0 && (
                <div style={{
                    marginBottom: 24, padding: '14px 18px', borderRadius: 12,
                    background: 'rgba(59,130,246,0.06)', border: '1px solid rgba(59,130,246,0.15)',
                }}>
                    <div style={{ fontSize: 13, fontWeight:600, color: 'var(--blue)', marginBottom: 10 }}>
                        Yaklasan Randevular (Bugun)
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                        {stats.upcoming.map(u => (
                            <div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 13 }}>
                                <span className="mono" style={{ fontWeight:600, color: 'var(--text)', minWidth: 50 }}>
                                    {fmtDate(u.appointment_date).split(' ')[1]}
                                </span>
                                <span className="mono" style={{ color: 'var(--blue)', minWidth: 110 }}>{u.phone}</span>
                                <span style={{ color: 'var(--text-dim)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                    {u.customer_name || ''} {u.subject ? `- ${u.subject}` : ''}
                                </span>
                                <span style={{ fontSize: 11, color: 'var(--amber)', fontWeight:600 }}>{timeUntil(u.appointment_date)}</span>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* Filtreler */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
                <select className="form-select" value={filterStatus} onChange={e =>setFilterStatus(e.target.value)} style={{ width: 160, padding: '6px 10px', fontSize: 13 }}>
                    <option value="">Tum Durumlar</option>
                    {Object.entries(STATUS_MAP).map(([k, v]) => (
                        <option key={k} value={k}>{v.label}</option>
                    ))}
                </select>
                <input type="date" className="form-input" value={filterDate} onChange={e =>setFilterDate(e.target.value)} style={{ width: 160, padding: '6px 10px', fontSize: 13 }} />
                {(filterStatus || filterDate) && (
                    <button className="btn outline" onClick={() => { setFilterStatus(''); setFilterDate(''); }} style={{ padding: '6px 12px', fontSize: 12 }}>Temizle</button>
                )}
                <div style={{ flex: 1 }} />
                <button className="btn outline" onClick={load} style={{ padding: '6px 14px', fontSize: 12 }}>
                    {loading ? '...' : 'Yenile'}
                </button>
            </div>

            {/* Tablo */}
            <div className="table-container">
                <table>
                    <thead>
                        <tr>
                            <th style={{ width: 50 }}>#</th>
                            <th style={{ width: 130 }}>Telefon</th>
                            <th>Musteri</th>
                            <th style={{ width: 140 }}>Randevu Tarihi</th>
                            <th style={{ width: 70 }}>Kalan</th>
                            <th>Konu</th>
                            <th style={{ width: 90 }}>Durum</th>
                            <th style={{ width: 80 }}>Kaynak</th>
                            <th style={{ width: 190, minWidth: 190 }}>Islemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        {appointments.length === 0 ? (
                            <tr><td colSpan={9} style={{ textAlign: 'center', padding: 40, color: 'var(--text-dim)' }}>
                                {loading ? 'Yukleniyor...' : 'Randevu bulunamadi'}
                            </td></tr>
                        ) : appointments.map(a => (
                            <tr key={a.id}>
                                <td className="mono" style={{ fontSize: 12, color: 'var(--text-dim)' }}>{a.id}</td>
                                <td className="mono" style={{ fontWeight:600, fontSize: 13 }}>{a.phone}</td>
                                <td style={{ fontSize: 13 }}>{a.customer_name || <span style={{ color: 'var(--text-dim)', fontStyle: 'italic' }}>-</span>}</td>
                                <td className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{fmtDate(a.appointment_date)}</td>
                                <td style={{ fontSize: 11, fontWeight: 600, color: a.status === 'pending' ? 'var(--amber)' : 'var(--text-dim)' }}>
                                    {a.status === 'pending' ? timeUntil(a.appointment_date) : '-'}
                                </td>
                                <td style={{ fontSize: 12, color: 'var(--text-dim)', maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                    {a.subject || '-'}
                                </td>
                                <td><StatusBadge status={a.status} /></td>
                                <td style={{ fontSize: 11, color: 'var(--text-dim)' }}>
                                    {a.source_call_uuid ? <span title={a.source_call_uuid}>AI Cagri</span> : 'Manuel'}
                                </td>
                                <td style={{ whiteSpace: 'nowrap' }}>
                                    <div style={{ display: 'flex', gap: 4 }}>
                                        {(a.status === 'pending' || a.status === 'confirmed' || a.status === 'missed') && (
                                            <button className="btn-sm" onClick={() =>callAppt(a.id)} title="Simdi ara" style={{ fontSize: 11 }}>
                                                 Ara
                                            </button>
                                        )}
                                        {(a.status === 'pending' || a.status === 'confirmed') && (
                                            <button className="btn-sm outline" onClick={() =>cancelAppt(a.id)} title="Iptal et" style={{ fontSize: 11 }}>
                                                Iptal
                                            </button>
                                        )}
                                        <button className="btn-sm outline" onClick={() =>deleteAppt(a.id)} title="Sil" style={{ fontSize: 11, color: 'var(--red)', borderColor: 'rgba(239,68,68,0.3)' }}>
                                            Sil
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>

            {/* Modal */}
            {modal && (
                <NewAppointmentModal
                    onClose={() =>setModal(false)}
                    onSave={() => { toast('Randevu olusturuldu', 'success'); setModal(false); load(); }}
                />
            )}
        </div>
    );
}

window.AppointmentsTab = AppointmentsTab;
