import React, { ReactElement, useState, useRef, useEffect } from 'react';

function dateInputValueToTs(s: string): number {
  const [y, mo, day] = s.split('-').map(Number);
  return new Date(y, mo - 1, day).getTime();
}
import { useLiveQuery } from 'dexie-react-hooks';
import {
  createTodo,
  fromDBPage,
} from '../../db/pages';
import { db } from '../../db/db';
import { logger } from '../../utils/logger';
import {
  Button,
  Checkbox,
  Input,
  Sheet,
  Stack,
  Select,
  Option,
  Typography,
} from '@mui/joy';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlus } from '@fortawesome/free-solid-svg-icons';
import PageRow from '../flexView/pagelists/pagerow/PageRow';

const TodoView = (): ReactElement => {
  const [showCompleted, setShowCompleted] = useState(false);
  const [addingNew, setAddingNew] = useState(false);
  const [newTitle, setNewTitle] = useState('');
  const [newPriority, setNewPriority] = useState<number | null>(null);
  const [newDueDate, setNewDueDate] = useState('');
  const [addError, setAddError] = useState<string | null>(null);
  const newTitleRef = useRef<HTMLInputElement>(null);

  const todos = useLiveQuery(
    () =>
      showCompleted
        ? db.pages.where('completionStatus').anyOf(['pending', 'completed']).toArray()
        : db.pages.where('completionStatus').equals('pending').toArray(),
    [showCompleted]
  );

  const sorted = (todos ?? []).slice().sort((a, b) => {
    const pa = a.priority ?? 999;
    const pb = b.priority ?? 999;
    if (pa !== pb) return pa - pb;
    const ca = a.creationDate ?? 0;
    const cb = b.creationDate ?? 0;
    return cb - ca;
  });

  useEffect(() => {
    if (addingNew) {
      newTitleRef.current?.focus();
    }
  }, [addingNew]);

  const handleAdd = async () => {
    const title = newTitle.trim();
    if (!title) return;
    const dueDate = newDueDate ? dateInputValueToTs(newDueDate) : undefined;
    setAddError(null);
    try {
      await createTodo(title, newPriority ?? undefined, dueDate);
      setNewTitle('');
      setNewPriority(null);
      setNewDueDate('');
      setAddingNew(false);
    } catch (e: unknown) {
      logger.error('[TodoView] createTodo failed', e);
      setAddError(e instanceof Error ? e.message : 'Failed to create todo');
    }
  };

  const handleNewKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      void handleAdd();
    } else if (e.key === 'Escape') {
      setAddingNew(false);
      setNewTitle('');
      setNewPriority(null);
      setNewDueDate('');
      setAddError(null);
    }
  };

  return (
    <Sheet sx={{ p: 2, height: '100%', overflowY: 'auto' }}>
      <Stack spacing={1}>
        <Stack direction="row" spacing={2} alignItems="center">
          <Button
            size="sm"
            variant="outlined"
            startDecorator={<FontAwesomeIcon icon={faPlus} />}
            onClick={() => setAddingNew(true)}
          >
            Add Todo
          </Button>
          <Checkbox
            size="sm"
            label="Show completed"
            checked={showCompleted}
            onChange={(e) => setShowCompleted(e.target.checked)}
          />
        </Stack>

        {addingNew && (
          <Stack direction="row" spacing={1} alignItems="center" sx={{ py: 0.5 }}>
            <Input
              size="sm"
              placeholder="Todo title..."
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              onKeyDown={handleNewKeyDown}
              slotProps={{ input: { ref: newTitleRef } }}
              sx={{ flex: 1 }}
            />
            <Select
              size="sm"
              value={newPriority}
              onChange={(_: React.SyntheticEvent | null, val: number | null) => setNewPriority(val)}
              sx={{ minWidth: 90 }}
            >
              <Option value={null}>-</Option>
              <Option value={1}><span style={{ color: '#c0392b', fontWeight: 'bold' }}>P0</span></Option>
              <Option value={2}><span style={{ color: '#e67e22', fontWeight: 'bold' }}>P1</span></Option>
              <Option value={3}><span style={{ color: '#7f8c8d', fontWeight: 'bold' }}>P2</span></Option>
            </Select>
            <Input
              size="sm"
              type="date"
              value={newDueDate}
              onChange={(e) => setNewDueDate(e.target.value)}
              sx={{ width: 140 }}
            />
            <Button size="sm" onClick={() => void handleAdd()} disabled={newTitle.trim() === ''}>
              Add
            </Button>
            <Button
              size="sm"
              variant="plain"
              color="neutral"
              onClick={() => {
                setAddingNew(false);
                setNewTitle('');
                setNewPriority(null);
                setNewDueDate('');
                setAddError(null);
              }}
            >
              Cancel
            </Button>
          </Stack>
        )}

        {addError && (
          <Typography level="body-sm" color="danger">
            {addError}
          </Typography>
        )}

        {sorted.length === 0 && !addingNew && (
          <Typography level="body-sm" sx={{ color: 'text.tertiary', mt: 2 }}>
            No todos yet. Click "Add Todo" to create one.
          </Typography>
        )}

        {sorted.map((todo) => (
          <PageRow key={todo.url} page={fromDBPage(todo)} />
        ))}
      </Stack>
    </Sheet>
  );
};

export default TodoView;
