"use client";

import { useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { CheckSquare, Square, Plus } from "lucide-react";
import { createTask, toggleTask } from "@/lib/api";
import AddTaskModal from "../AddTaskModal";

interface Task {
  id: number;
  title: string;
  done: boolean;
  priority?: number;
}

interface Props {
  tasks: Task[];
  onUpdate: () => void;
}

export default function TasksCard({ tasks, onUpdate }: Props) {
  const [modalOpen, setModalOpen] = useState(false);
  const [localTasks, setLocalTasks] = useState<Task[]>(tasks);

  const handleToggle = useCallback(
    async (task: Task) => {
      setLocalTasks((prev) =>
        prev.map((t) => (t.id === task.id ? { ...t, done: !t.done } : t))
      );
      await toggleTask(task.id, !task.done);
      onUpdate();
    },
    [onUpdate]
  );

  const handleAdd = useCallback(
    async (title: string) => {
      const newTask = { id: Date.now(), title, done: false };
      setLocalTasks((prev) => [newTask, ...prev]);
      await createTask(title);
      onUpdate();
    },
    [onUpdate]
  );

  const pending = localTasks.filter((t) => !t.done);
  const done = localTasks.filter((t) => t.done);

  return (
    <>
      <motion.div
        className="glass-card p-5 h-full flex flex-col"
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        whileHover={{ scale: 1.005 }}
      >
        <div className="flex items-center justify-between mb-4">
          <div>
            <div className="flex items-center gap-2">
              <CheckSquare size={18} color="#6366f1" />
              <span
                className="text-sm font-semibold"
                style={{ color: "var(--text-primary)" }}
              >
                Задачи сегодня
              </span>
            </div>
            <div
              className="text-xs mt-0.5"
              style={{ color: "var(--text-secondary)" }}
            >
              {pending.length} осталось из {localTasks.length}
            </div>
          </div>
          <motion.button
            onClick={() => setModalOpen(true)}
            className="w-8 h-8 rounded-lg flex items-center justify-center"
            style={{
              background: "linear-gradient(135deg, #6366f1, #8b5cf6)",
              boxShadow: "0 0 12px rgba(99,102,241,0.4)",
            }}
            whileTap={{ scale: 0.85 }}
          >
            <Plus size={16} color="white" />
          </motion.button>
        </div>

        <div className="flex-1 overflow-y-auto space-y-2 pr-1">
          <AnimatePresence>
            {localTasks.length === 0 && (
              <motion.div
                className="text-center py-8"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
              >
                <div className="text-3xl mb-2">🎉</div>
                <div
                  className="text-sm"
                  style={{ color: "var(--text-secondary)" }}
                >
                  Всё сделано!
                </div>
              </motion.div>
            )}

            {localTasks.map((task) => (
              <motion.div
                key={task.id}
                layout
                initial={{ opacity: 0, x: -10 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: 10, height: 0 }}
                className="flex items-center gap-3 px-3 py-2.5 rounded-xl cursor-pointer"
                style={{
                  background: task.done
                    ? "rgba(16,185,129,0.06)"
                    : "rgba(255,255,255,0.04)",
                  border: task.done
                    ? "1px solid rgba(16,185,129,0.15)"
                    : "1px solid rgba(255,255,255,0.06)",
                }}
                onClick={() => handleToggle(task)}
                whileTap={{ scale: 0.97 }}
              >
                {task.done ? (
                  <CheckSquare size={16} color="#10b981" />
                ) : (
                  <Square size={16} color="var(--text-secondary)" />
                )}
                <span
                  className="text-xs font-medium flex-1 leading-snug"
                  style={{
                    color: task.done
                      ? "var(--text-secondary)"
                      : "var(--text-primary)",
                    textDecoration: task.done ? "line-through" : "none",
                  }}
                >
                  {task.title}
                </span>
              </motion.div>
            ))}
          </AnimatePresence>
        </div>
      </motion.div>

      <AddTaskModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onAdd={handleAdd}
      />
    </>
  );
}
