import { useState } from 'react';
import {
  useTodos,
  usePendingTodos,
  useCompletedTodos,
  useCreateTodo,
  useUpdateTodo,
  useDeleteTodo,
} from '@/hooks/useTodos';
import { Button } from '@/components/Button';
import { Input } from '@/components/Input';
import { Card } from '@/components/Card';
import { Plus, Trash2, Check } from 'lucide-react';
import type { TodoStatus, TodoPriority } from '@/types';

export default function TodosPage() {
  const { data: pendingTodos } = usePendingTodos();
  const { data: completedTodos } = useCompletedTodos();
  const createTodo = useCreateTodo();
  const updateTodo = useUpdateTodo();
  const deleteTodo = useDeleteTodo();
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [filter, setFilter] = useState<TodoStatus | 'all'>('all');

  const [formData, setFormData] = useState({
    title: '',
    description: '',
    priority: 'medium' as TodoPriority,
  });

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await createTodo.mutateAsync(formData);
      setFormData({ title: '', description: '', priority: 'medium' });
      setShowCreateForm(false);
    } catch (err: any) {
      alert(err.message || '创建失败');
    }
  };

  const handleStatusChange = async (id: string, status: TodoStatus) => {
    try {
      await updateTodo.mutateAsync({ id, data: { status } });
    } catch (err: any) {
      alert(err.message || '更新失败');
    }
  };

  const handleDelete = async (id: string) => {
    if (confirm('确定要删除这个待办吗？')) {
      try {
        await deleteTodo.mutateAsync(id);
      } catch (err: any) {
        alert(err.message || '删除失败');
      }
    }
  };

  const filteredTodos =
    filter === 'all'
      ? [...(pendingTodos || []), ...(completedTodos || [])]
      : filter === 'pending'
        ? pendingTodos || []
        : completedTodos || [];

  const priorityColors: Record<TodoPriority, string> = {
    low: 'bg-blue-100 text-blue-800',
    medium: 'bg-yellow-100 text-yellow-800',
    high: 'bg-orange-100 text-orange-800',
    urgent: 'bg-red-100 text-red-800',
  };

  const priorityLabels: Record<TodoPriority, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">待办事项</h1>
          <p className="mt-1 text-sm text-gray-600">管理您的任务</p>
        </div>
        <Button onClick={() => setShowCreateForm(!showCreateForm)}>
          <Plus className="mr-2 h-4 w-4" />
          新建待办
        </Button>
      </div>

      {/* Filters */}
      <div className="flex gap-2">
        <Button
          size="sm"
          variant={filter === 'all' ? 'primary' : 'secondary'}
          onClick={() => setFilter('all')}
        >
          全部
        </Button>
        <Button
          size="sm"
          variant={filter === 'pending' ? 'primary' : 'secondary'}
          onClick={() => setFilter('pending')}
        >
          待办
        </Button>
        <Button
          size="sm"
          variant={filter === 'completed' ? 'primary' : 'secondary'}
          onClick={() => setFilter('completed')}
        >
          已完成
        </Button>
      </div>

      {/* Create Form */}
      {showCreateForm && (
        <Card title="新建待办">
          <form onSubmit={handleCreate} className="space-y-4">
            <Input
              label="标题"
              value={formData.title}
              onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              placeholder="待办标题"
              required
            />
            <div>
              <label className="mb-2 block text-sm font-medium text-gray-700">
                描述
              </label>
              <textarea
                className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                rows={3}
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="待办描述"
              />
            </div>
            <div>
              <label className="mb-2 block text-sm font-medium text-gray-700">
                优先级
              </label>
              <select
                className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                value={formData.priority}
                onChange={(e) => setFormData({ ...formData, priority: e.target.value as TodoPriority })}
              >
                <option value="low">低</option>
                <option value="medium">中</option>
                <option value="high">高</option>
                <option value="urgent">紧急</option>
              </select>
            </div>
            <div className="flex justify-end gap-3">
              <Button
                type="button"
                variant="secondary"
                onClick={() => setShowCreateForm(false)}
              >
                取消
              </Button>
              <Button type="submit" loading={createTodo.isPending}>
                创建
              </Button>
            </div>
          </form>
        </Card>
      )}

      {/* Todos List */}
      <div className="space-y-3">
        {filteredTodos.map((todo) => (
          <Card key={todo.id} variant="bordered">
            <div className="flex items-start gap-3">
              <button
                onClick={() =>
                  handleStatusChange(
                    todo.id,
                    todo.status === 'pending' ? 'completed' : 'pending'
                  )
                }
                className={`mt-1 rounded border-2 ${
                  todo.status === 'completed'
                    ? 'border-green-500 bg-green-500 text-white'
                    : 'border-gray-300 hover:border-green-500'
                } flex h-5 w-5 items-center justify-center transition-colors`}
              >
                {todo.status === 'completed' && <Check className="h-3 w-3" />}
              </button>
              <div className="flex-1">
                <div className="flex items-start justify-between">
                  <h3
                    className={`font-semibold ${
                      todo.status === 'completed' ? 'text-gray-500 line-through' : 'text-gray-900'
                    }`}
                  >
                    {todo.title}
                  </h3>
                  <div className="flex items-center gap-2">
                    <span
                      className={`rounded px-2 py-1 text-xs font-medium ${
                        priorityColors[todo.priority]
                      }`}
                    >
                      {priorityLabels[todo.priority]}
                    </span>
                    <button
                      onClick={() => handleDelete(todo.id)}
                      className="text-gray-400 hover:text-red-600"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                </div>
                {todo.description && (
                  <p className="mt-1 text-sm text-gray-600">{todo.description}</p>
                )}
              </div>
            </div>
          </Card>
        ))}
      </div>

      {filteredTodos.length === 0 && (
        <Card variant="bordered">
          <p className="text-center text-gray-500">暂无待办事项</p>
        </Card>
      )}
    </div>
  );
}
