'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import api, { Task } from '@/lib/api';
import { PlusIcon, CheckIcon, XIcon, ClockIcon, TrashIcon } from '@/components/ui/Icons';

function formatDateTime(dtStr: string): string {
  try {
    const dt = new Date(dtStr);
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1);

    const timeStr = dt.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });

    if (dt.toDateString() === now.toDateString()) return `Today at ${timeStr}`;
    if (dt.toDateString() === tomorrow.toDateString()) return `Tomorrow at ${timeStr}`;

    return dt.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' }) + ` at ${timeStr}`;
  } catch {
    return dtStr;
  }
}

function isPast(dtStr: string): boolean {
  try {
    return new Date(dtStr) < new Date();
  } catch {
    return false;
  }
}

export default function TasksPage() {
  const router = useRouter();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [showCompleted, setShowCompleted] = useState(false);

  const loadTasks = async (status: string) => {
    try {
      const data = await api.tasks.list(status);
      setTasks(data);
    } catch (err) {
      console.error('Failed to load tasks:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadTasks(showCompleted ? 'all' : 'pending');
  }, [showCompleted]);

  const handleMarkDone = async (task: Task) => {
    try {
      await api.tasks.update(task.id, { status: 'completed' });
      setTasks(prev => prev.filter(t => t.id !== task.id));
    } catch (err) {
      console.error('Failed to update task:', err);
    }
  };

  const handleCancel = async (task: Task) => {
    try {
      await api.tasks.update(task.id, { status: 'cancelled' });
      setTasks(prev => prev.filter(t => t.id !== task.id));
    } catch (err) {
      console.error('Failed to cancel task:', err);
    }
  };

  const handleDelete = async (task: Task) => {
    if (!confirm(`Delete "${task.title}"?`)) return;
    try {
      await api.tasks.delete(task.id);
      setTasks(prev => prev.filter(t => t.id !== task.id));
    } catch (err) {
      console.error('Failed to delete task:', err);
    }
  };

  const activeTasks = tasks.filter(t => t.status === 'pending' || t.status === 'notified');
  const doneTasks = tasks.filter(t => t.status === 'completed' || t.status === 'cancelled');

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-950">
      <header className="bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 sticky top-0 z-10">
        <div className="flex items-center justify-between px-4 py-3">
          <h1 className="text-xl font-bold text-gray-900 dark:text-gray-100">Tasks</h1>
          <Link
            href="/dashboard/tasks/new"
            className="flex items-center gap-1 text-indigo-600 dark:text-indigo-400 font-medium text-sm"
          >
            <PlusIcon size={18} />
            Add Task
          </Link>
        </div>
      </header>

      <div className="p-4 space-y-4">
        {isLoading ? (
          <div className="flex justify-center py-12">
            <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin" />
          </div>
        ) : activeTasks.length === 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-xl p-8 shadow-sm text-center">
            <ClockIcon size={40} className="mx-auto mb-3 text-gray-300 dark:text-gray-600" />
            <p className="text-gray-500 dark:text-gray-400 mb-4">No upcoming tasks</p>
            <Link
              href="/dashboard/tasks/new"
              className="inline-flex items-center gap-2 bg-indigo-600 text-white text-sm font-medium px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors"
            >
              <PlusIcon size={16} />
              Add your first task
            </Link>
          </div>
        ) : (
          <div className="space-y-3">
            {activeTasks.map(task => (
              <div
                key={task.id}
                className={`bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm border-l-4 ${
                  task.status === 'notified'
                    ? 'border-amber-400'
                    : isPast(task.scheduled_datetime)
                    ? 'border-red-400'
                    : 'border-indigo-400'
                }`}
              >
                <div className="flex items-start gap-3">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-gray-900 dark:text-gray-100 truncate">{task.title}</h3>
                    {task.description && (
                      <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">{task.description}</p>
                    )}
                    <div className="flex items-center gap-2 mt-1.5">
                      <ClockIcon size={13} className="text-gray-400 flex-shrink-0" />
                      <span className={`text-sm ${isPast(task.scheduled_datetime) && task.status === 'pending' ? 'text-red-500 dark:text-red-400' : 'text-gray-500 dark:text-gray-400'}`}>
                        {formatDateTime(task.scheduled_datetime)}
                      </span>
                      {task.status === 'notified' && (
                        <span className="text-xs bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 rounded-full">
                          Notified
                        </span>
                      )}
                      {task.reminder_minutes_before > 0 && (
                        <span className="text-xs text-gray-400 dark:text-gray-500">
                          +{task.reminder_minutes_before}m reminder
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-1 flex-shrink-0">
                    <button
                      onClick={() => handleMarkDone(task)}
                      className="p-2 text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-lg transition-colors"
                      title="Mark done"
                    >
                      <CheckIcon size={18} />
                    </button>
                    <button
                      onClick={() => handleCancel(task)}
                      className="p-2 text-gray-400 dark:text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                      title="Cancel"
                    >
                      <XIcon size={18} />
                    </button>
                    <button
                      onClick={() => handleDelete(task)}
                      className="p-2 text-red-400 dark:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                      title="Delete"
                    >
                      <TrashIcon size={18} />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Show completed toggle */}
        {!isLoading && (
          <button
            onClick={() => setShowCompleted(!showCompleted)}
            className="w-full text-sm text-gray-500 dark:text-gray-400 py-2 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
          >
            {showCompleted ? 'Hide completed' : `Show completed${doneTasks.length > 0 ? ` (${doneTasks.length})` : ''}`}
          </button>
        )}

        {/* Completed tasks */}
        {showCompleted && doneTasks.length > 0 && (
          <div className="space-y-2">
            <h2 className="text-sm font-medium text-gray-500 dark:text-gray-400 px-1">Completed / Cancelled</h2>
            {doneTasks.map(task => (
              <div key={task.id} className="bg-white dark:bg-gray-800 rounded-xl p-4 shadow-sm opacity-60 flex items-center justify-between">
                <div>
                  <p className="text-gray-700 dark:text-gray-300 line-through">{task.title}</p>
                  <p className="text-xs text-gray-400 dark:text-gray-500">{formatDateTime(task.scheduled_datetime)}</p>
                </div>
                <button
                  onClick={() => handleDelete(task)}
                  className="p-1.5 text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
                >
                  <TrashIcon size={16} />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
