// Log-or-clear completion for a DERIVED follow-up (owner's design call
// 2026-08-10): optionally log the contact that happened, set the next date
// or leave it blank to clear — the account's callback_date is the record.
const FollowupCompleteModal = ({ followup, onComplete, onClose }) => {
    const [logType, setLogType]   = React.useState('phone'); // '' = don't log
    const [note, setNote]         = React.useState('');
    const [nextDate, setNextDate] = React.useState('');
    const [saving, setSaving]     = React.useState(false);

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true);
        try {
            await onComplete({
                accountId: followup.account_id,
                comm: logType ? {
                    account_id: followup.account_id, type: logType, direction: 'outbound',
                    subject: 'Follow-up', content: note.trim() || 'Follow-up completed.',
                } : null,
                nextDate: nextDate || null,
            });
            onClose();
        } catch (err) { alert(err.message); }
        finally { setSaving(false); }
    };

    return (
        <Modal isOpen={true} onClose={onClose} title={`Follow up — ${followup.account_name}`}>
            <form onSubmit={handleSave}>
                <div className="form-group">
                    <label className="form-label">Log this contact as</label>
                    <select className="form-input" value={logType} onChange={e => setLogType(e.target.value)}>
                        <option value="phone">Phone call</option>
                        <option value="email">Email</option>
                        <option value="meeting">Meeting</option>
                        <option value="note">Note</option>
                        <option value="">Don't log — just complete</option>
                    </select>
                </div>
                {logType && (
                    <div className="form-group">
                        <label className="form-label">What happened?</label>
                        <textarea className="form-input form-textarea" value={note}
                                  placeholder="Left a voicemail about the renewal…"
                                  onChange={e => setNote(e.target.value)} />
                    </div>
                )}
                <div className="form-group">
                    <label className="form-label">Next follow-up (blank = none needed)</label>
                    <input type="date" className="form-input" value={nextDate} onChange={e => setNextDate(e.target.value)} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem', marginTop: '0.75rem' }}>
                    <button type="button" className="btn btn-secondary" onClick={onClose}>Cancel</button>
                    <button type="submit" className="btn btn-primary" disabled={saving}>
                        <i className="fas fa-check"></i> Complete
                    </button>
                </div>
            </form>
        </Modal>
    );
};

// loadError/onRetryLoad: tasks are loaded by MainApp (this view is props-fed),
// so the fetch-failure banner state has to arrive from above too.
const TasksView = ({ tasks, followups, onCompleteFollowup, loadError, onRetryLoad, onSelectAccount, onComplete, onDelete, onCreateTask, onUpdateTask }) => {
    const [filter, setFilter]       = React.useState('all');
    const [showNewTask, setShowNewTask] = React.useState(false);
    const [editTask, setEditTask]   = React.useState(null); // task being edited
    const [signoffTask, setSignoffTask] = React.useState(null); // task awaiting sign-off in the modal
    // Completion email (review policy, 2026-08-09): signing off a pipeline
    // task pops the template compose prefilled for that account — the human
    // glances and sends ("abc.com is live!"). Closing without sending = skip.
    const [notifyFor, setNotifyFor] = React.useState(null);     // { account, contacts }

    const [completingFollowup, setCompletingFollowup] = React.useState(null); // derived row mid-completion

    const today = new Date(); today.setHours(0, 0, 0, 0);
    const endOfWeek = new Date(today); endOfWeek.setDate(today.getDate() + 7);

    // Derived follow-up rows (accounts.callback_date) ride the same list as
    // real tasks — same filters, same counts. `_followup` marks them; their
    // due_date is the account's callback_date.
    const followupRows = (followups || []).map(f => ({
        _followup: true, id: `fu-${f.account_id}`,
        account_id: f.account_id, account_name: f.account_name,
        due_date: f.callback_date, assigned_to_name: f.assigned_to_name,
    }));
    const allItems = [...tasks, ...followupRows];

    // parseDateOnly (api.js), not new Date(): due_date is a DATE column and the
    // bare parse lands at UTC midnight — a day early in any US timezone (IMP-10).
    const dueLocal  = (t) => { const d = parseDateOnly(t.due_date); d.setHours(0,0,0,0); return d; };
    const overdueCt = allItems.filter(t => t.due_date && dueLocal(t) < today).length;
    const todayCt   = allItems.filter(t => t.due_date && dueLocal(t).getTime() === today.getTime()).length;
    const weekCt    = allItems.filter(t => {
        if (!t.due_date) return false;
        const d = dueLocal(t);
        return d >= today && d <= endOfWeek;
    }).length;

    const filtered = allItems.filter(t => {
        if (filter === 'all') return true;
        if (!t.due_date) return false;
        const d = dueLocal(t);
        if (filter === 'overdue') return d < today;
        if (filter === 'today')   return d.getTime() === today.getTime();
        if (filter === 'week')    return d >= today && d <= endOfWeek;
        return true;
    }).slice().sort((a, b) => {
        if (!a.due_date && !b.due_date) return 0;
        if (!a.due_date) return 1;
        if (!b.due_date) return -1;
        return new Date(a.due_date) - new Date(b.due_date);
    });


    const handleCreate = async (formData) => {
        await onCreateTask(formData);
        setShowNewTask(false);
    };

    return (
        <div className="tasks-page">

            {loadError && (
                <LoadErrorBanner what="tasks" hasData={tasks.length > 0} onRetry={onRetryLoad} />
            )}

            {/* No in-view title — the topbar names the view (rail UI rule);
                the filter chips already carry the open/overdue counts. */}
            <div className="tasks-filter-bar">
                {[
                    { id: 'all',     label: `All (${allItems.length})` },
                    { id: 'overdue', label: `Overdue (${overdueCt})`, danger: overdueCt > 0 },
                    { id: 'today',   label: `Due Today (${todayCt})` },
                    { id: 'week',    label: `This Week (${weekCt})` },
                ].map(f => (
                    <button
                        key={f.id}
                        className={`filter-chip ${filter === f.id ? 'active' : ''} ${f.danger && filter !== f.id ? 'danger' : ''}`}
                        onClick={() => setFilter(f.id)}
                    >
                        {f.label}
                    </button>
                ))}
                <button className="btn btn-primary btn-small" style={{ marginLeft: 'auto' }} onClick={() => setShowNewTask(true)}>
                    <i className="fas fa-plus"></i> New Task
                </button>
            </div>

            <div className="tasks-list">
                {filtered.length === 0 ? (
                    <div className="empty-state" style={{ marginTop: '3rem' }}>
                        <i className="fas fa-calendar-check empty-state-icon"></i>
                        <h3 className="empty-state-title">
                            {filter === 'all' ? 'All caught up!' : 'No tasks match this filter'}
                        </h3>
                        <p className="empty-state-message">
                            {filter === 'all' ? 'No open tasks right now.' : 'Try a different filter or create a new task.'}
                        </p>
                    </div>
                ) : (<div className="tasks-list-container">{filtered.map(task => {
                    const statusClass = getTaskStatusClass(task.due_date);
                    const prioColor  = PRIORITY_COLOR[task.priority] || '#6b7280';

                    // Derived follow-up row — no task record behind it; the
                    // account's callback_date is the source of truth.
                    if (task._followup) return (
                        <div key={task.id} className={`task-row ${statusClass}`}>
                            <div className="task-row-priority" style={{ background: '#0ea5e9' }}></div>
                            <div className="task-row-body">
                                <div className="task-row-main">
                                    <button className="task-account-link"
                                            onClick={() => onSelectAccount({ id: task.account_id })}
                                            title={`Open ${task.account_name}`}>
                                        <i className="fas fa-building"></i>
                                        {task.account_name}
                                    </button>
                                    <span className="task-row-divider">·</span>
                                    <span className="task-row-title"><i className="fas fa-phone" style={{ marginRight: '0.35rem', fontSize: '0.75rem' }}></i>Follow up</span>
                                </div>
                                <div className="task-row-meta">
                                    <span className="badge secondary" style={{ fontSize: '0.7rem' }} title="From the account's Next Follow-up date">follow-up</span>
                                    {task.assigned_to_name && <span style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>{task.assigned_to_name}</span>}
                                    <span className={`task-due-label ${statusClass}`}>
                                        <i className="fas fa-calendar-alt"></i> {formatDate(task.due_date)}
                                        {statusClass === 'overdue' && ' — Overdue'}
                                        {statusClass === 'today'   && ' — Due Today'}
                                    </span>
                                </div>
                            </div>
                            <div className="task-row-actions">
                                <button className="btn btn-secondary btn-small" title="Log the contact and set or clear the next date"
                                        onClick={() => setCompletingFollowup(followups.find(f => f.account_id === task.account_id))}>
                                    <i className="fas fa-check"></i> Complete
                                </button>
                            </div>
                        </div>
                    );

                    return (
                        <div key={task.id} className={`task-row ${statusClass}`}>
                            <div className="task-row-priority" style={{ background: prioColor }}></div>

                            <div className="task-row-body">
                                <div className="task-row-main">
                                    <button
                                        className="task-account-link"
                                        onClick={() => task.account_id && onSelectAccount({ id: task.account_id })}
                                        title={task.account_name ? `Open ${task.account_name}` : 'Account not found'}
                                    >
                                        <i className="fas fa-building"></i>
                                        {task.account_name || 'Unknown Account'}
                                    </button>
                                    <span className="task-row-divider">·</span>
                                    <span className="task-row-title">{task.title}</span>
                                </div>

                                {task.notes && (
                                    <div className="task-row-notes">{task.notes}</div>
                                )}

                                <div className="task-row-meta">
                                    <span className="task-prio-badge" style={{ background: prioColor }}>
                                        {task.priority}
                                    </span>
                                    <span className="badge secondary" style={{ fontSize: '0.7rem' }}>
                                        {task.task_type.replace(/_/g, ' ')}
                                    </span>
                                    {task.requires_signoff && (
                                        <span className="badge secondary" style={{ fontSize: '0.7rem' }} title="Completing this task requires initials + a note of what was done">
                                            <i className="fas fa-clipboard-check"></i> sign-off
                                        </span>
                                    )}
                                    {task.due_date && (
                                        <span className={`task-due-label ${statusClass}`}>
                                            <i className="fas fa-calendar-alt"></i> {formatDate(task.due_date)}
                                            {statusClass === 'overdue' && ' — Overdue'}
                                            {statusClass === 'today'   && ' — Due Today'}
                                        </span>
                                    )}
                                </div>
                            </div>

                            <div className="task-row-actions">
                                <button className="btn btn-primary btn-small" onClick={() => task.requires_signoff ? setSignoffTask(task) : onComplete(task.id)} title={task.requires_signoff ? 'Requires sign-off' : 'Mark complete'}>
                                    <i className="fas fa-check"></i> Done
                                </button>
                                {/* Pipeline-born (sign-off-gated) tasks stay exactly as the
                                    pipeline wrote them — no edit (server enforces too). */}
                                {!task.requires_signoff && (
                                    <button className="btn btn-secondary btn-small" onClick={() => setEditTask(task)} title="Edit task">
                                        <i className="fas fa-pencil-alt"></i>
                                    </button>
                                )}
                                <button className="btn btn-danger btn-small" onClick={() => onDelete(task.id)} title="Delete task">
                                    <i className="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    );
                })}</div>)}
            </div>

            {completingFollowup && (
                <FollowupCompleteModal
                    followup={completingFollowup}
                    onComplete={onCompleteFollowup}
                    onClose={() => setCompletingFollowup(null)}
                />
            )}

            {signoffTask && (
                <TaskSignoffModal
                    task={signoffTask}
                    onClose={() => setSignoffTask(null)}
                    onConfirm={async (signoff) => {
                        const doneTask = signoffTask;
                        await onComplete(doneTask.id, signoff);
                        setSignoffTask(null);
                        // Offer the client notification for the account the
                        // task belonged to — fetched fresh (tasks only carry
                        // the account's name, not its contacts). Any fetch
                        // failure just skips the offer; the task is already
                        // completed either way.
                        if (doneTask.account_id) {
                            try {
                                const [acct, contacts] = await Promise.all([
                                    api.getAccount(doneTask.account_id),
                                    api.getContacts({ account_id: doneTask.account_id }).catch(() => []),
                                ]);
                                setNotifyFor({ account: acct, contacts });
                            } catch { /* offer skipped, completion already done */ }
                        }
                    }}
                />
            )}

            {notifyFor && (
                <TemplateSendModal
                    account={notifyFor.account}
                    contacts={notifyFor.contacts}
                    onSent={() => setNotifyFor(null)}
                    onClose={() => setNotifyFor(null)}
                />
            )}

            <Modal isOpen={showNewTask} onClose={() => setShowNewTask(false)} title="New Task">
                <TaskForm
                    onSubmit={handleCreate}
                    onCancel={() => setShowNewTask(false)}
                />
            </Modal>

            {editTask && (
                <Modal isOpen={true} onClose={() => setEditTask(null)} title="Edit Task">
                    <TaskForm
                        initial={editTask}
                        onSubmit={async (fd) => { await onUpdateTask(editTask.id, fd); setEditTask(null); }}
                        onCancel={() => setEditTask(null)}
                    />
                </Modal>
            )}
        </div>
    );
};
