import { router } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import AppLayout from '@/layouts/AppLayout';
import { useTranslator } from '@/lib/i18n';
import { ExportMenu } from '@/components/export-menu';

interface Task {
    id: string;
    title: string;
    phase: string;
    phase_order: number;
    sort_order: number;
    completed: boolean;
    completed_at?: string;
}

interface CustomPhase {
    key: string;
    label: string;
    sort_order: number;
}

interface PhaseConfig {
    labels: Record<string, string>;
    hidden: string[];
    custom_phases: CustomPhase[];
}

interface Props {
    wedding: any;
    tasksByPhase: Record<string, Task[]>;
    phaseConfig: PhaseConfig;
}

export default function Checklist({ wedding, tasksByPhase, phaseConfig }: Props) {
    const t = useTranslator();
    const [editing, setEditing] = useState(false);
    const [renamingPhase, setRenamingPhase] = useState<string | null>(null);
    const [renameValue, setRenameValue] = useState('');
    const [addingPhase, setAddingPhase] = useState(false);
    const [newPhaseLabel, setNewPhaseLabel] = useState('');
    const [addTaskFor, setAddTaskFor] = useState<string | null>(null);
    const [newTaskTitle, setNewTaskTitle] = useState('');
    // Default to a single flat list — not all weddings follow a 9–12-month-out
    // template. Couples who want phase grouping can switch via the toggle.
    const [viewMode, setViewMode] = useState<'flat' | 'phases'>('flat');

    const labels = phaseConfig?.labels ?? {};
    const hidden = phaseConfig?.hidden ?? [];
    const customPhases = phaseConfig?.custom_phases ?? [];

    const phases = useMemo(() => {
        const grouped = Object.entries(tasksByPhase).map(([phase, tasks]) => ({
            phase,
            tasks,
            phase_order: tasks[0]?.phase_order ?? 0,
        }));
        // Add custom phases that have no tasks yet
        for (const cp of customPhases) {
            if (!grouped.find(g => g.phase === cp.key)) {
                grouped.push({ phase: cp.key, tasks: [], phase_order: cp.sort_order ?? 99 });
            }
        }
        return grouped
            .filter(g => !hidden.includes(g.phase))
            .sort((a, b) => a.phase_order - b.phase_order);
    }, [tasksByPhase, customPhases, hidden]);

    const allTasks = Object.values(tasksByPhase).flat();
    const completedCount = allTasks.filter(t => t.completed).length;
    const total = allTasks.length;

    const labelFor = (phase: string) => labels[phase] ?? phase;

    function toggle(task: Task) {
        router.patch(`/weddings/${wedding.id}/checklist/${task.id}`, {}, { preserveScroll: true });
    }

    function deleteTask(task: Task) {
        router.delete(`/weddings/${wedding.id}/checklist/${task.id}`, { preserveScroll: true });
    }

    function addTask(phase: string) {
        if (!newTaskTitle.trim()) return;
        const phase_order = phases.find(p => p.phase === phase)?.phase_order ?? 99;
        router.post(`/weddings/${wedding.id}/checklist`,
            { phase, phase_order, title: newTaskTitle.trim() },
            { preserveScroll: true, onSuccess: () => { setNewTaskTitle(''); setAddTaskFor(null); } });
    }

    function saveConfig(next: Partial<PhaseConfig>) {
        const payload: Record<string, unknown> = {
            labels:        next.labels        ?? labels,
            hidden:        next.hidden        ?? hidden,
            custom_phases: next.custom_phases ?? customPhases,
        };
        router.put(`/weddings/${wedding.id}/checklist/phase-config`, payload as never, { preserveScroll: true });
    }

    function commitRename(phase: string) {
        if (!renameValue.trim()) {
            setRenamingPhase(null);
            return;
        }
        const nextLabels = { ...labels, [phase]: renameValue.trim() };
        // If the rename matches the original phase string, drop the override
        if (renameValue.trim() === phase) delete nextLabels[phase];
        saveConfig({ labels: nextLabels });
        setRenamingPhase(null);
        setRenameValue('');
    }

    function deletePhase(phase: string) {
        const cnt = tasksByPhase[phase]?.length ?? 0;
        const msg = cnt > 0
            ? `Delete "${labelFor(phase)}" and its ${cnt} task${cnt === 1 ? '' : 's'}?`
            : `Hide "${labelFor(phase)}"?`;
        if (!confirm(msg)) return;
        router.delete(`/weddings/${wedding.id}/checklist/phases/${encodeURIComponent(phase)}`,
            { preserveScroll: true });
    }

    function addPhase() {
        if (!newPhaseLabel.trim()) return;
        const key = `custom_${Date.now()}`;
        const maxOrder = phases.reduce((m, p) => Math.max(m, p.phase_order), 0);
        const next = [...customPhases, { key, label: newPhaseLabel.trim(), sort_order: maxOrder + 1 }];
        saveConfig({ custom_phases: next });
        setNewPhaseLabel('');
        setAddingPhase(false);
    }

    return (
        <AppLayout wedding={wedding}>
            <div className="max-w-3xl mx-auto px-6 py-8">
                <div className="mb-8 flex items-start justify-between gap-4">
                    <div className="flex-1">
                        <h1 className="font-serif text-3xl mb-2">{t('checklist.title')}</h1>
                        <div className="flex items-center gap-4">
                            <div className="flex-1 bg-muted rounded-full h-2">
                                <div
                                    className="bg-primary h-2 rounded-full transition-all"
                                    style={{ width: `${total > 0 ? (completedCount / total) * 100 : 0}%` }}
                                />
                            </div>
                            <span className="text-sm text-muted-foreground whitespace-nowrap">
                                {completedCount} / {total} tasks
                            </span>
                        </div>
                    </div>
                    <div className="flex items-center gap-2">
                        <ExportMenu
                            filename="checklist"
                            title={t('checklist.title')}
                            rows={Object.values(tasksByPhase).flat()}
                            columns={[
                                { header: t('checklist.task'), value: (task: Task) => task.title },
                                { header: t('checklist.phase'), value: (task: Task) => phaseConfig?.labels?.[task.phase] ?? task.phase },
                                { header: t('checklist.task_completed'), value: (task: Task) => task.completed ? t('common.yes') : t('common.no') },
                            ]}
                        />
                        <button
                            onClick={() => setViewMode(m => m === 'flat' ? 'phases' : 'flat')}
                            className="text-sm px-3 py-1.5 rounded-lg border border-border hover:bg-muted whitespace-nowrap"
                            title={viewMode === 'flat' ? 'Group tasks by planning phase' : 'Show all tasks in one list'}
                        >
                            {viewMode === 'flat' ? 'Group by phase' : 'Single list'}
                        </button>
                        {viewMode === 'phases' && (
                            <button
                                onClick={() => setEditing(e => !e)}
                                className="text-sm px-3 py-1.5 rounded-lg border border-border hover:bg-muted whitespace-nowrap"
                            >
                                {editing ? t('checklist.done_editing') : t('checklist.edit_phases')}
                            </button>
                        )}
                    </div>
                </div>

                {/* Flat list — default. One simple list, add at the bottom. */}
                {viewMode === 'flat' && (
                    <div className="space-y-2">
                        {phases.flatMap(p => p.tasks).sort((a, b) => a.sort_order - b.sort_order).map((task) => (
                            <div key={task.id} className="group flex items-center gap-2">
                                <button
                                    onClick={() => toggle(task)}
                                    className={`flex-1 flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${
                                        task.completed
                                            ? 'bg-muted/50 border-border text-muted-foreground'
                                            : 'bg-card border-border hover:border-primary/40'
                                    }`}
                                >
                                    <span className={`w-5 h-5 rounded-full border-2 flex-shrink-0 flex items-center justify-center ${
                                        task.completed ? 'bg-primary border-primary text-white' : 'border-muted-foreground'
                                    }`}>
                                        {task.completed && (
                                            <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                                            </svg>
                                        )}
                                    </span>
                                    <span className={`text-sm ${task.completed ? 'line-through' : ''}`}>{task.title}</span>
                                </button>
                                <button
                                    onClick={() => deleteTask(task)}
                                    className="opacity-0 group-hover:opacity-100 text-red-500 hover:text-red-700 px-2 text-sm transition-opacity"
                                    title={t('checklist.delete_task')}
                                >×</button>
                            </div>
                        ))}
                        {/* Inline add */}
                        {addTaskFor === '__flat__' ? (
                            <div className="flex gap-2 pt-2">
                                <input
                                    autoFocus
                                    placeholder={t('checklist.new_task')}
                                    value={newTaskTitle}
                                    onChange={(e) => setNewTaskTitle(e.target.value)}
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') addTask(phases[0]?.phase ?? 'custom');
                                        if (e.key === 'Escape') { setAddTaskFor(null); setNewTaskTitle(''); }
                                    }}
                                    className="flex-1 px-3 py-2 rounded-lg border border-border bg-card text-sm outline-none focus:border-primary"
                                />
                                <button
                                    onClick={() => addTask(phases[0]?.phase ?? 'custom')}
                                    className="px-3 py-2 rounded-lg bg-primary text-primary-foreground text-sm"
                                >{t('common.add')}</button>
                            </div>
                        ) : (
                            <button
                                onClick={() => setAddTaskFor('__flat__')}
                                className="w-full p-2 text-sm text-muted-foreground hover:text-foreground border border-dashed border-border rounded-lg"
                            >+ Add task</button>
                        )}
                    </div>
                )}

                {/* Phase-grouped — opt-in for couples who want the structured view */}
                {viewMode === 'phases' && (
                <div className="space-y-8">
                    {phases.map(({ phase, tasks }) => {
                        const done = tasks.filter(t => t.completed).length;
                        return (
                            <div key={phase}>
                                <div className="flex items-center justify-between mb-3 gap-2">
                                    {renamingPhase === phase ? (
                                        <input
                                            autoFocus
                                            value={renameValue}
                                            onChange={(e) => setRenameValue(e.target.value)}
                                            onBlur={() => commitRename(phase)}
                                            onKeyDown={(e) => {
                                                if (e.key === 'Enter') commitRename(phase);
                                                if (e.key === 'Escape') { setRenamingPhase(null); setRenameValue(''); }
                                            }}
                                            className="font-semibold text-foreground bg-transparent border-b border-primary outline-none flex-1"
                                        />
                                    ) : (
                                        <h2 className="font-semibold text-foreground flex-1">{labelFor(phase)}</h2>
                                    )}
                                    <span className="text-xs text-muted-foreground">{done}/{tasks.length}</span>
                                    {editing && (
                                        <div className="flex gap-1">
                                            <button
                                                onClick={() => { setRenamingPhase(phase); setRenameValue(labelFor(phase)); }}
                                                className="text-xs text-muted-foreground hover:text-foreground px-1.5"
                                                title={t('checklist.rename')}
                                            >✎</button>
                                            <button
                                                onClick={() => deletePhase(phase)}
                                                className="text-xs text-red-500 hover:text-red-700 px-1.5"
                                                title={t('checklist.delete_phase')}
                                            >×</button>
                                        </div>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    {tasks.sort((a, b) => a.sort_order - b.sort_order).map((task) => (
                                        <div key={task.id} className="group flex items-center gap-2">
                                            <button
                                                onClick={() => toggle(task)}
                                                className={`flex-1 flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${
                                                    task.completed
                                                        ? 'bg-muted/50 border-border text-muted-foreground'
                                                        : 'bg-card border-border hover:border-primary/40'
                                                }`}
                                            >
                                                <span className={`w-5 h-5 rounded-full border-2 flex-shrink-0 flex items-center justify-center ${
                                                    task.completed ? 'bg-primary border-primary text-white' : 'border-muted-foreground'
                                                }`}>
                                                    {task.completed && (
                                                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                                                        </svg>
                                                    )}
                                                </span>
                                                <span className={`text-sm ${task.completed ? 'line-through' : ''}`}>
                                                    {task.title}
                                                </span>
                                            </button>
                                            {editing && (
                                                <button
                                                    onClick={() => deleteTask(task)}
                                                    className="text-red-500 hover:text-red-700 px-2 text-sm"
                                                    title={t('checklist.delete_task')}
                                                >×</button>
                                            )}
                                        </div>
                                    ))}
                                    {addTaskFor === phase ? (
                                        <div className="flex gap-2">
                                            <input
                                                autoFocus
                                                placeholder={t('checklist.new_task')}
                                                value={newTaskTitle}
                                                onChange={(e) => setNewTaskTitle(e.target.value)}
                                                onKeyDown={(e) => {
                                                    if (e.key === 'Enter') addTask(phase);
                                                    if (e.key === 'Escape') { setAddTaskFor(null); setNewTaskTitle(''); }
                                                }}
                                                className="flex-1 px-3 py-2 rounded-lg border border-border bg-card text-sm outline-none focus:border-primary"
                                            />
                                            <button
                                                onClick={() => addTask(phase)}
                                                className="px-3 py-2 rounded-lg bg-primary text-primary-foreground text-sm"
                                            >{t('common.add')}</button>
                                        </div>
                                    ) : editing && (
                                        <button
                                            onClick={() => setAddTaskFor(phase)}
                                            className="w-full p-2 text-sm text-muted-foreground hover:text-foreground border border-dashed border-border rounded-lg"
                                        >+ Add task</button>
                                    )}
                                </div>
                            </div>
                        );
                    })}

                    {editing && (addingPhase ? (
                        <div className="flex gap-2 pt-4 border-t border-border">
                            <input
                                autoFocus
                                placeholder={t('checklist.new_phase_name')}
                                value={newPhaseLabel}
                                onChange={(e) => setNewPhaseLabel(e.target.value)}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') addPhase();
                                    if (e.key === 'Escape') { setAddingPhase(false); setNewPhaseLabel(''); }
                                }}
                                className="flex-1 px-3 py-2 rounded-lg border border-border bg-card text-sm outline-none focus:border-primary"
                            />
                            <button
                                onClick={addPhase}
                                className="px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm"
                            >{t('checklist.add_phase')}</button>
                        </div>
                    ) : (
                        <button
                            onClick={() => setAddingPhase(true)}
                            className="w-full py-3 text-sm text-muted-foreground hover:text-foreground border border-dashed border-border rounded-lg"
                        >+ Add custom phase</button>
                    ))}
                </div>
                )}
            </div>
        </AppLayout>
    );
}
