import React, { useCallback, useEffect, useRef, useState } from 'react';
import { getTodos, addTodo, updateTodo, deleteTodo, clearTodos } from '../../api';
import { useIsMobile } from '../../hooks/useIsMobile';
import SwipeableView from '../../components/SwipeableView';
import FAB from '../../components/FAB';
import MobileSheet from '../../components/MobileSheet';
import PullToRefresh from '../../components/PullToRefresh';
import './Todo.css';

const ACTIVE_COLUMNS = [
    { id: 'todo', label: '할 일' },
    { id: 'in_progress', label: '진행 중' },
];
const ALL_COLUMNS = [
    ...ACTIVE_COLUMNS,
    { id: 'done', label: '완료' },
];

const emptyForm = { title: '', description: '' };

const toDateStr = (iso) => {
    if (!iso) return '';
    return new Date(iso).toISOString().slice(0, 10); // YYYY-MM-DD
};

const Todo = () => {
    const isMobile = useIsMobile();
    const [todos, setTodos] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [form, setForm] = useState(emptyForm);
    const [formOpen, setFormOpen] = useState(false);
    const [addSheetOpen, setAddSheetOpen] = useState(false);
    const [saving, setSaving] = useState(false);
    const [dragging, setDragging] = useState(null);
    const [dragOver, setDragOver] = useState(null);
    const [doneDate, setDoneDate] = useState(''); // '' = 전체
    const [confirmClear, setConfirmClear] = useState(false);
    const dragItem = useRef(null);

    const load = useCallback(async () => {
        setLoading(true);
        setError('');
        try {
            const data = await getTodos();
            setTodos(Array.isArray(data) ? data : []);
        } catch (err) {
            setError(err?.message ?? String(err));
        } finally {
            setLoading(false);
        }
    }, []);

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

    const handleAdd = async (e) => {
        e.preventDefault();
        if (!form.title.trim()) return;
        setSaving(true);
        try {
            const created = await addTodo({ ...form, status: 'todo' });
            setTodos((prev) => [created, ...prev]);
            setForm(emptyForm);
            setFormOpen(false);
        } catch (err) {
            setError(err?.message ?? String(err));
        } finally {
            setSaving(false);
        }
    };

    const handleMove = async (id, newStatus) => {
        setTodos((prev) =>
            prev.map((t) =>
                t.id === id
                    ? { ...t, status: newStatus, updated_at: new Date().toISOString() }
                    : t
            )
        );
        try {
            await updateTodo(id, { status: newStatus, updated_at: new Date().toISOString() });
        } catch {
            load();
        }
    };

    const handleDelete = async (id) => {
        setTodos((prev) => prev.filter((t) => t.id !== id));
        try {
            await deleteTodo(id);
        } catch {
            load();
        }
    };

    const handleClear = async () => {
        setConfirmClear(false);
        try {
            await clearTodos();
            setTodos((prev) => prev.filter((t) => t.status !== 'done'));
        } catch (err) {
            setError(err?.message ?? String(err));
        }
    };

    /* ── Drag & Drop ─────────────────────────────────────────────── */
    const onDragStart = (e, todo) => {
        dragItem.current = todo;
        setDragging(todo.id);
        e.dataTransfer.effectAllowed = 'move';
    };

    const onDragEnd = () => {
        setDragging(null);
        setDragOver(null);
        dragItem.current = null;
    };

    const onDragOver = (e, colId) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
        setDragOver(colId);
    };

    const onDrop = (e, colId) => {
        e.preventDefault();
        if (dragItem.current && dragItem.current.status !== colId) {
            handleMove(dragItem.current.id, colId);
        }
        setDragOver(null);
    };

    const byStatus = (status) => todos.filter((t) => t.status === status);

    /* ── 완료 필터 ─────────────────────────────────────────────────── */
    const doneTodos = todos.filter((t) => {
        if (t.status !== 'done') return false;
        if (!doneDate) return true;
        const ref = t.updated_at || t.created_at;
        return toDateStr(ref) === doneDate;
    });

    /* 완료 항목에서 날짜 목록 추출 (필터 select용) */
    const doneDates = [...new Set(
        todos
            .filter((t) => t.status === 'done')
            .map((t) => toDateStr(t.updated_at || t.created_at))
            .filter(Boolean)
    )].sort((a, b) => b.localeCompare(a)); // 최신순

    const formatDate = (iso) => {
        if (!iso) return '';
        return new Date(iso).toLocaleDateString('ko-KR', { month: 'short', day: 'numeric' });
    };

    const renderCard = (todo, colId) => (
        <div
            key={todo.id}
            className={`todo-card${dragging === todo.id ? ' is-dragging' : ''}`}
            draggable
            onDragStart={(e) => onDragStart(e, todo)}
            onDragEnd={onDragEnd}
        >
            <p className="todo-card__title">{todo.title}</p>
            {todo.description && (
                <p className="todo-card__desc">{todo.description}</p>
            )}
            <div className="todo-card__footer">
                <span className="todo-card__date">
                    {formatDate(todo.created_at)}
                </span>
                <div className="todo-card__actions">
                    {ALL_COLUMNS.filter((c) => c.id !== colId).map((c) => (
                        <button
                            key={c.id}
                            type="button"
                            className={`todo-card__btn${isMobile ? ' todo-card__btn--labeled' : ''}`}
                            title={`${c.label}으로 이동`}
                            onClick={() => handleMove(todo.id, c.id)}
                        >
                            <span className="todo-card__btn-icon">{c.id === 'todo' ? '↩' : c.id === 'in_progress' ? '▶' : '✓'}</span>
                            {isMobile && <span className="todo-card__btn-label">{c.label}</span>}
                        </button>
                    ))}
                    <button
                        type="button"
                        className={`todo-card__btn todo-card__btn--danger${isMobile ? ' todo-card__btn--labeled' : ''}`}
                        title="삭제"
                        onClick={() => handleDelete(todo.id)}
                    >
                        <span className="todo-card__btn-icon">✕</span>
                        {isMobile && <span className="todo-card__btn-label">삭제</span>}
                    </button>
                </div>
            </div>
        </div>
    );

    /* ── 칸반 컬럼 렌더러 (재사용) ── */
    const renderColumn = (col) => {
        const items = byStatus(col.id);
        return (
            <div
                key={col.id}
                className={`todo-col${dragOver === col.id ? ' is-drag-over' : ''}`}
                onDragOver={(e) => onDragOver(e, col.id)}
                onDrop={(e) => onDrop(e, col.id)}
            >
                <div className="todo-col__head">
                    <span className="todo-col__title">{col.label}</span>
                    <span className="todo-col__count">{items.length}</span>
                </div>
                <div className="todo-col__body">
                    {items.length === 0 && (
                        <p className="todo-col__empty">
                            {isMobile ? '아직 항목이 없습니다' : '드래그하여 이동'}
                        </p>
                    )}
                    {items.map((todo) => renderCard(todo, col.id))}
                </div>
            </div>
        );
    };

    /* ── 추가 폼 (공통) ── */
    const addForm = (
        <form className="todo-form" onSubmit={async (e) => { await handleAdd(e); setAddSheetOpen(false); }}>
            <label className="todo-form__field">
                <span>제목 *</span>
                <input
                    type="text"
                    placeholder="태스크 제목을 입력하세요"
                    value={form.title}
                    onChange={(e) => setForm((v) => ({ ...v, title: e.target.value }))}
                    required
                />
            </label>
            <label className="todo-form__field">
                <span>설명</span>
                <textarea
                    placeholder="설명 (선택)"
                    value={form.description}
                    rows={3}
                    onChange={(e) => setForm((v) => ({ ...v, description: e.target.value }))}
                />
            </label>
            <div className="todo-form__actions">
                <button
                    type="submit"
                    className="button primary"
                    disabled={saving || !form.title.trim()}
                >
                    {saving ? '저장 중...' : '추가'}
                </button>
            </div>
        </form>
    );

    return (
        <PullToRefresh onRefresh={load}>
        <div className="todo-page">
            {/* 툴바 */}
            <div className="todo-toolbar">
                <button
                    type="button"
                    className="button primary"
                    onClick={() => setFormOpen((v) => !v)}
                >
                    {formOpen ? '취소' : '+ 할일 추가'}
                </button>
                <button
                    type="button"
                    className="button ghost"
                    onClick={() => {
                        const doneCount = todos.filter(t => t.status === 'done').length;
                        if (doneCount === 0) return;
                        if (isMobile) { setConfirmClear(true); } else { handleClear(); }
                    }}
                >
                    완료 비우기
                </button>
            </div>

            {/* 추가 폼 (데스크탑) */}
            {formOpen && !isMobile && addForm}

            {error && <p className="todo-error">{error}</p>}
            {loading && todos.length === 0 && <p className="todo-loading">불러오는 중...</p>}

            {/* 모바일: SwipeableView 칸반 */}
            {isMobile ? (
                <div className="todo-swipe-board">
                    <SwipeableView
                        tabs={[
                            { key: 'todo',        label: '할 일',  content: renderColumn({ id: 'todo', label: '할 일' }) },
                            { key: 'in_progress', label: '진행 중', content: renderColumn({ id: 'in_progress', label: '진행 중' }) },
                            { key: 'done',        label: '완료',   content: (
                                <div className="todo-done-panel">
                                    <div className="todo-done-panel__head">
                                        <div className="todo-done-panel__title-row">
                                            <span className="todo-col__title">완료</span>
                                            <span className="todo-col__count">{doneTodos.length}</span>
                                            {doneTodos.length > 0 && (
                                                <button
                                                    type="button"
                                                    className="todo-done-panel__clear-btn"
                                                    onClick={() => setConfirmClear(true)}
                                                >
                                                    비우기
                                                </button>
                                            )}
                                        </div>
                                        <div className="todo-done-panel__filter">
                                            <button type="button" className={`todo-date-btn${doneDate === '' ? ' is-active' : ''}`} onClick={() => setDoneDate('')}>전체</button>
                                            {doneDates.map((d) => (
                                                <button key={d} type="button" className={`todo-date-btn${doneDate === d ? ' is-active' : ''}`} onClick={() => setDoneDate(d)}>
                                                    {new Date(d + 'T00:00:00').toLocaleDateString('ko-KR', { month: 'short', day: 'numeric' })}
                                                </button>
                                            ))}
                                        </div>
                                    </div>
                                    <div className="todo-done-panel__body">
                                        {doneTodos.length === 0 ? (
                                            <p className="todo-col__empty">{doneDate ? '해당 날짜에 완료된 항목이 없습니다' : '완료된 항목이 없습니다'}</p>
                                        ) : (
                                            doneTodos.map((todo) => renderCard(todo, 'done'))
                                        )}
                                    </div>
                                </div>
                            )},
                        ]}
                    />
                </div>
            ) : (
                <>
                    {/* 데스크탑: 활성 보드 (할 일 + 진행 중) */}
                    <div className="todo-board">
                        {ACTIVE_COLUMNS.map((col) => renderColumn(col))}
                    </div>

                    {/* 완료 패널 */}
                    <div
                        className={`todo-done-panel${dragOver === 'done' ? ' is-drag-over' : ''}`}
                        onDragOver={(e) => onDragOver(e, 'done')}
                        onDrop={(e) => onDrop(e, 'done')}
                    >
                        <div className="todo-done-panel__head">
                            <div className="todo-done-panel__title-row">
                                <span className="todo-col__title">완료</span>
                                <span className="todo-col__count">{doneTodos.length}</span>
                                {doneDates.length > 0 && doneDate === '' && (
                                    <span className="todo-done-panel__total-hint">
                                        전체 {todos.filter(t => t.status === 'done').length}건
                                    </span>
                                )}
                            </div>
                            <div className="todo-done-panel__filter">
                                <button
                                    type="button"
                                    className={`todo-date-btn${doneDate === '' ? ' is-active' : ''}`}
                                    onClick={() => setDoneDate('')}
                                >
                                    전체
                                </button>
                                {doneDates.map((d) => (
                                    <button
                                        key={d}
                                        type="button"
                                        className={`todo-date-btn${doneDate === d ? ' is-active' : ''}`}
                                        onClick={() => setDoneDate(d)}
                                    >
                                        {new Date(d + 'T00:00:00').toLocaleDateString('ko-KR', { month: 'short', day: 'numeric' })}
                                    </button>
                                ))}
                                <input
                                    type="date"
                                    className="todo-date-input"
                                    value={doneDate}
                                    onChange={(e) => setDoneDate(e.target.value)}
                                    title="날짜 직접 선택"
                                />
                            </div>
                        </div>
                        <div className="todo-done-panel__body">
                            {doneTodos.length === 0 ? (
                                <p className="todo-col__empty">
                                    {doneDate ? '해당 날짜에 완료된 항목이 없습니다' : (isMobile ? '완료된 항목이 없습니다' : '드래그하여 이동')}
                                </p>
                            ) : (
                                doneTodos.map((todo) => renderCard(todo, 'done'))
                            )}
                        </div>
                    </div>
                </>
            )}

            {/* 모바일: 추가 바텀시트 */}
            <MobileSheet
                open={addSheetOpen}
                onClose={() => { setAddSheetOpen(false); setForm(emptyForm); }}
                title="할일 추가"
            >
                {addForm}
            </MobileSheet>

            {/* 모바일: 완료 비우기 확인 시트 */}
            <MobileSheet
                open={confirmClear}
                onClose={() => setConfirmClear(false)}
                title="완료 항목 비우기"
                snap="half"
            >
                <div className="todo-confirm-sheet">
                    <p className="todo-confirm-sheet__msg">
                        완료된 항목 {todos.filter(t => t.status === 'done').length}건을 모두 삭제합니다.
                    </p>
                    <div className="todo-confirm-sheet__actions">
                        <button type="button" className="button ghost" onClick={() => setConfirmClear(false)}>취소</button>
                        <button type="button" className="button danger" onClick={handleClear}>삭제</button>
                    </div>
                </div>
            </MobileSheet>

            <FAB onClick={() => setAddSheetOpen(true)} label="할일 추가" />
        </div>
        </PullToRefresh>
    );
};

export default Todo;
