"use client";

import React, { useState, useEffect } from "react";
import { Plus, Check, X, Clock, AlertCircle, GripVertical, ChevronDown } from "lucide-react";

interface TodoItem {
  id: string;
  title: string;
  description?: string;
  priority: "urgent" | "high" | "normal" | "low";
  status: "pending" | "in_progress" | "completed";
  assignedTo?: string;
  dueDate?: string;
  createdAt: string;
  updatedAt: string;
  completedAt?: string;
  isUrgent: boolean;
  order: number;
}

interface TodoStats {
  total: number;
  pending: number;
  inProgress: number;
  completed: number;
  urgent: number;
  overdue: number;
}

export default function TodoWidget() {
  const [todos, setTodos] = useState<TodoItem[]>([]);
  const [stats, setStats] = useState<TodoStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<"all" | "pending" | "in_progress" | "completed">("all");
  const [showAddForm, setShowAddForm] = useState(false);
  const [newTodo, setNewTodo] = useState({
    title: "",
    description: "",
    priority: "normal" as TodoItem["priority"],
    isUrgent: false,
    dueDate: "",
    assignedTo: "",
  });

  useEffect(() => {
    fetchTodos();
    const interval = setInterval(fetchTodos, 30000); // 30초마다 갱신
    return () => clearInterval(interval);
  }, [filter]);

  const fetchTodos = async () => {
    try {
      const token = localStorage.getItem("authToken");
      const filterParam = filter !== "all" ? `?status=${filter}` : "";
      const response = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        const result = await response.json();
        setTodos(result.data || []);
        setStats(result.stats);
      }
    } catch (error) {
      // console.error("To-Do 로딩 오류:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleAddTodo = async () => {
    if (!newTodo.title.trim()) return;

    try {
      const token = localStorage.getItem("authToken");
      const response = await fetch("http://localhost:9771/api/todos", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(newTodo),
      });

      if (response.ok) {
        setNewTodo({
          title: "",
          description: "",
          priority: "normal",
          isUrgent: false,
          dueDate: "",
          assignedTo: "",
        });
        setShowAddForm(false);
        fetchTodos();
      }
    } catch (error) {
      // console.error("To-Do 추가 오류:", error);
    }
  };

  const handleUpdateStatus = async (id: string, status: TodoItem["status"]) => {
    try {
      const token = localStorage.getItem("authToken");
      const response = await fetch(`http://localhost:9771/api/todos/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status }),
      });

      if (response.ok) {
        fetchTodos();
      }
    } catch (error) {
      // console.error("상태 업데이트 오류:", error);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("이 To-Do를 삭제하시겠습니까?")) return;

    try {
      const token = localStorage.getItem("authToken");
      const response = await fetch(`http://localhost:9771/api/todos/${id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (response.ok) {
        fetchTodos();
      }
    } catch (error) {
      // console.error("To-Do 삭제 오류:", error);
    }
  };

  const getPriorityColor = (priority: TodoItem["priority"]) => {
    switch (priority) {
      case "urgent":
        return "bg-red-100 text-red-700 border-red-300";
      case "high":
        return "bg-orange-100 text-orange-700 border-orange-300";
      case "normal":
        return "bg-blue-100 text-blue-700 border-blue-300";
      case "low":
        return "bg-gray-100 text-gray-700 border-gray-300";
    }
  };

  const getPriorityIcon = (priority: TodoItem["priority"]) => {
    switch (priority) {
      case "urgent":
        return "🔴";
      case "high":
        return "🟠";
      case "normal":
        return "🟡";
      case "low":
        return "🟢";
    }
  };

  const getTimeRemaining = (dueDate: string) => {
    const now = new Date();
    const due = new Date(dueDate);
    const diff = due.getTime() - now.getTime();
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(hours / 24);

    if (diff < 0) return "⏰ 기한 초과";
    if (days > 0) return `📅 ${days}일 남음`;
    if (hours > 0) return `⏱️ ${hours}시간 남음`;
    return "⚠️ 오늘 마감";
  };

  if (loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-gray-500">로딩 중...</div>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col bg-gradient-to-br from-slate-50 to-blue-50">
      {/* 헤더 */}
      <div className="border-b border-gray-200 bg-white px-4 py-3">
        <div className="mb-3 flex items-center justify-between">
          <h3 className="text-lg font-bold text-gray-800">✅ To-Do / 긴급 지시</h3>
          <button
            onClick={() => setShowAddForm(!showAddForm)}
            className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-white transition-colors hover:bg-primary/90"
          >
            <Plus className="h-4 w-4" />
            추가
          </button>
        </div>

        {/* 통계 */}
        {stats && (
          <div className="grid grid-cols-4 gap-2 text-xs">
            <div className="rounded bg-blue-50 px-2 py-1.5 text-center">
              <div className="font-bold text-blue-700">{stats.pending}</div>
              <div className="text-blue-600">대기</div>
            </div>
            <div className="rounded bg-amber-50 px-2 py-1.5 text-center">
              <div className="font-bold text-amber-700">{stats.inProgress}</div>
              <div className="text-amber-600">진행중</div>
            </div>
            <div className="rounded bg-red-50 px-2 py-1.5 text-center">
              <div className="font-bold text-red-700">{stats.urgent}</div>
              <div className="text-red-600">긴급</div>
            </div>
            <div className="rounded bg-rose-50 px-2 py-1.5 text-center">
              <div className="font-bold text-rose-700">{stats.overdue}</div>
              <div className="text-rose-600">지연</div>
            </div>
          </div>
        )}

        {/* 필터 */}
        <div className="mt-3 flex gap-2">
          {(["all", "pending", "in_progress", "completed"] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`rounded px-3 py-1 text-xs font-medium transition-colors ${
                filter === f
                  ? "bg-primary text-white"
                  : "bg-gray-100 text-gray-600 hover:bg-gray-200"
              }`}
            >
              {f === "all" ? "전체" : f === "pending" ? "대기" : f === "in_progress" ? "진행중" : "완료"}
            </button>
          ))}
        </div>
      </div>

      {/* 추가 폼 */}
      {showAddForm && (
        <div className="border-b border-gray-200 bg-white p-4">
          <div className="space-y-2">
            <input
              type="text"
              placeholder="할 일 제목*"
              value={newTodo.title}
              onChange={(e) => setNewTodo({ ...newTodo, title: e.target.value })}
              className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
            />
            <textarea
              placeholder="상세 설명 (선택)"
              value={newTodo.description}
              onChange={(e) => setNewTodo({ ...newTodo, description: e.target.value })}
              className="w-full rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
              rows={2}
            />
            <div className="grid grid-cols-2 gap-2">
              <select
                value={newTodo.priority}
                onChange={(e) => setNewTodo({ ...newTodo, priority: e.target.value as TodoItem["priority"] })}
                className="rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
              >
                <option value="low">🟢 낮음</option>
                <option value="normal">🟡 보통</option>
                <option value="high">🟠 높음</option>
                <option value="urgent">🔴 긴급</option>
              </select>
              <input
                type="datetime-local"
                value={newTodo.dueDate}
                onChange={(e) => setNewTodo({ ...newTodo, dueDate: e.target.value })}
                className="rounded border border-gray-300 px-3 py-2 text-sm focus:border-primary focus:outline-none"
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="flex items-center gap-2 text-sm">
                <input
                  type="checkbox"
                  checked={newTodo.isUrgent}
                  onChange={(e) => setNewTodo({ ...newTodo, isUrgent: e.target.checked })}
                  className="h-4 w-4 rounded border-gray-300"
                />
                <span className="text-red-600 font-medium">긴급 지시</span>
              </label>
            </div>
            <div className="flex gap-2">
              <button
                onClick={handleAddTodo}
                className="flex-1 rounded bg-primary px-4 py-2 text-sm text-white hover:bg-primary/90"
              >
                추가
              </button>
              <button
                onClick={() => setShowAddForm(false)}
                className="rounded bg-gray-200 px-4 py-2 text-sm text-gray-700 hover:bg-gray-300"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      )}

      {/* To-Do 리스트 */}
      <div className="flex-1 overflow-y-auto p-4">
        {todos.length === 0 ? (
          <div className="flex h-full items-center justify-center text-gray-400">
            <div className="text-center">
              <div className="mb-2 text-4xl">📝</div>
              <div>할 일이 없습니다</div>
            </div>
          </div>
        ) : (
          <div className="space-y-2">
            {todos.map((todo) => (
              <div
                key={todo.id}
                className={`group relative rounded-lg border-2 bg-white p-3 shadow-sm transition-all hover:shadow-md ${
                  todo.isUrgent ? "border-red-400" : "border-gray-200"
                } ${todo.status === "completed" ? "opacity-60" : ""}`}
              >
                <div className="flex items-start gap-3">
                  {/* 우선순위 아이콘 */}
                  <div className="mt-1 text-lg">{getPriorityIcon(todo.priority)}</div>

                  {/* 내용 */}
                  <div className="flex-1">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1">
                        <div className={`font-medium ${todo.status === "completed" ? "line-through" : ""}`}>
                          {todo.isUrgent && <span className="mr-1 text-red-600">⚡</span>}
                          {todo.title}
                        </div>
                        {todo.description && (
                          <div className="mt-1 text-xs text-gray-600">{todo.description}</div>
                        )}
                        {todo.dueDate && (
                          <div className="mt-1 text-xs text-gray-500">{getTimeRemaining(todo.dueDate)}</div>
                        )}
                      </div>

                      {/* 액션 버튼 */}
                      <div className="flex gap-1">
                        {todo.status !== "completed" && (
                          <button
                            onClick={() => handleUpdateStatus(todo.id, "completed")}
                            className="rounded p-1 text-green-600 hover:bg-green-50"
                            title="완료"
                          >
                            <Check className="h-4 w-4" />
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(todo.id)}
                          className="rounded p-1 text-red-600 hover:bg-red-50"
                          title="삭제"
                        >
                          <X className="h-4 w-4" />
                        </button>
                      </div>
                    </div>

                    {/* 상태 변경 */}
                    {todo.status !== "completed" && (
                      <div className="mt-2 flex gap-1">
                        <button
                          onClick={() => handleUpdateStatus(todo.id, "pending")}
                          className={`rounded px-2 py-1 text-xs ${
                            todo.status === "pending"
                              ? "bg-blue-100 text-blue-700"
                              : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                          }`}
                        >
                          대기
                        </button>
                        <button
                          onClick={() => handleUpdateStatus(todo.id, "in_progress")}
                          className={`rounded px-2 py-1 text-xs ${
                            todo.status === "in_progress"
                              ? "bg-amber-100 text-amber-700"
                              : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                          }`}
                        >
                          진행중
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

