"use client";

import React, { useState, useEffect } from "react";
import { Plus, Check, X, Clock, AlertCircle, GripVertical, ChevronDown, Calendar as CalendarIcon } from "lucide-react";
import { DashboardElement } from "@/components/admin/dashboard/types";
import { useDashboard } from "@/contexts/DashboardContext";

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;
}

interface TodoWidgetProps {
  element?: DashboardElement;
}

export default function TodoWidget({ element }: TodoWidgetProps) {
  // Context에서 선택된 날짜 가져오기
  const { selectedDate } = useDashboard();
  
  const [todos, setTodos] = useState<TodoItem[]>([]);
  const [internalTodos, setInternalTodos] = useState<TodoItem[]>([]); // 내장 API 투두
  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, selectedDate]); // selectedDate도 의존성에 추가

  const fetchTodos = async () => {
    try {
      const token = localStorage.getItem("authToken");
      const userLang = localStorage.getItem("userLang") || "KR";
      
      // 내장 API 투두 항상 조회 (외부 DB 모드에서도)
      const filterParam = filter !== "all" ? `?status=${filter}` : "";
      const internalResponse = await fetch(`http://localhost:9771/api/todos${filterParam}`, {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      
      let internalData: TodoItem[] = [];
      if (internalResponse.ok) {
        const result = await internalResponse.json();
        internalData = result.data || [];
        setInternalTodos(internalData);
      }
      
      // 외부 DB 조회 (dataSource가 설정된 경우)
      if (element?.dataSource?.query) {
        // console.log("🔍 TodoWidget - 외부 DB 조회 시작");
        // console.log("📝 Query:", element.dataSource.query);
        // console.log("🔗 ConnectionId:", element.dataSource.externalConnectionId);
        // console.log("🔗 ConnectionType:", element.dataSource.connectionType);
        
        // 현재 DB vs 외부 DB 분기
        const apiUrl = element.dataSource.connectionType === "external" && element.dataSource.externalConnectionId
          ? `http://localhost:9771/api/external-db/query?userLang=${userLang}`
          : `http://localhost:9771/api/dashboards/execute-query?userLang=${userLang}`;
        
        const requestBody = element.dataSource.connectionType === "external" && element.dataSource.externalConnectionId
          ? {
              connectionId: parseInt(element.dataSource.externalConnectionId),
              query: element.dataSource.query,
            }
          : {
              query: element.dataSource.query,
            };

        // console.log("🌐 API URL:", apiUrl);
        // console.log("📦 Request Body:", requestBody);

        const response = await fetch(apiUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
          body: JSON.stringify(requestBody),
        });

        // console.log("📡 Response status:", response.status);

        if (response.ok) {
          const result = await response.json();
          // console.log("✅ API 응답:", result);
          // console.log("📦 result.data:", result.data);
          // console.log("📦 result.data.rows:", result.data?.rows);
          
          // API 응답 형식에 따라 데이터 추출
          const rows = result.data?.rows || result.data || [];
          // console.log("📊 추출된 rows:", rows);
          
          const externalTodos = mapExternalDataToTodos(rows);
          // console.log("📋 변환된 Todos:", externalTodos);
          // console.log("📋 변환된 Todos 개수:", externalTodos.length);
          
          // 외부 DB 데이터 + 내장 데이터 합치기
          const mergedTodos = [...externalTodos, ...internalData];
          setTodos(mergedTodos);
          setStats(calculateStatsFromTodos(mergedTodos));
          
          // console.log("✅ setTodos, setStats 호출 완료!");
        } else {
          const errorText = await response.text();
          // console.error("❌ API 오류:", errorText);
        }
      } 
      // 내장 API만 조회 (기본)
      else {
        setTodos(internalData);
        setStats(calculateStatsFromTodos(internalData));
      }
    } catch (error) {
      // console.error("To-Do 로딩 오류:", error);
    } finally {
      setLoading(false);
    }
  };

  // 외부 DB 데이터를 TodoItem 형식으로 변환
  const mapExternalDataToTodos = (data: any[]): TodoItem[] => {
    return data.map((row, index) => ({
      id: row.id || `todo-${index}`,
      title: row.title || row.task || row.name || "제목 없음",
      description: row.description || row.desc || row.content,
      priority: row.priority || "normal",
      status: row.status || "pending",
      assignedTo: row.assigned_to || row.assignedTo || row.user,
      dueDate: row.due_date || row.dueDate || row.deadline,
      createdAt: row.created_at || row.createdAt || new Date().toISOString(),
      updatedAt: row.updated_at || row.updatedAt || new Date().toISOString(),
      completedAt: row.completed_at || row.completedAt,
      isUrgent: row.is_urgent || row.isUrgent || row.urgent || false,
      order: row.display_order || row.order || index,
    }));
  };

  // Todo 배열로부터 통계 계산
  const calculateStatsFromTodos = (todoList: TodoItem[]): TodoStats => {
    return {
      total: todoList.length,
      pending: todoList.filter((t) => t.status === "pending").length,
      inProgress: todoList.filter((t) => t.status === "in_progress").length,
      completed: todoList.filter((t) => t.status === "completed").length,
      urgent: todoList.filter((t) => t.isUrgent).length,
      overdue: todoList.filter((t) => {
        if (!t.dueDate) return false;
        return new Date(t.dueDate) < new Date() && t.status !== "completed";
      }).length,
    };
  };

  // 외부 DB 조회 여부 확인
  const isExternalData = !!element?.dataSource?.query;

  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}`,
        },
      });

      // 응답이 성공이거나, 500 에러여도 실제로는 삭제되었을 수 있으므로 목록 새로고침
      if (response.ok || response.status === 500) {
        // 약간의 딜레이 후 새로고침 (백엔드 처리 완료 대기)
        setTimeout(() => {
          fetchTodos();
        }, 300);
      }
    } catch (error) {
      // 네트워크 에러여도 삭제되었을 수 있으므로 새로고침
      setTimeout(() => {
        fetchTodos();
      }, 300);
    }
  };

  const getPriorityColor = (priority: TodoItem["priority"]) => {
    switch (priority) {
      case "urgent":
        return "bg-destructive/10 text-destructive border-destructive";
      case "high":
        return "bg-warning/10 text-warning border-warning";
      case "normal":
        return "bg-primary/10 text-primary border-primary";
      case "low":
        return "bg-muted text-foreground border-border";
    }
  };

  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 "⚠️ 오늘 마감";
  };

  // 선택된 날짜로 필터링
  const filteredTodos = selectedDate
    ? todos.filter((todo) => {
        if (!todo.dueDate) return false;
        const todoDate = new Date(todo.dueDate);
        return (
          todoDate.getFullYear() === selectedDate.getFullYear() &&
          todoDate.getMonth() === selectedDate.getMonth() &&
          todoDate.getDate() === selectedDate.getDate()
        );
      })
    : todos;

  const formatSelectedDate = () => {
    if (!selectedDate) return null;
    const year = selectedDate.getFullYear();
    const month = selectedDate.getMonth() + 1;
    const day = selectedDate.getDate();
    return `${year}년 ${month}월 ${day}일`;
  };

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

  return (
    <div className="flex h-full flex-col bg-background">
      {/* 제목 - 항상 표시 */}
      <div className="border-b border-border bg-background px-4 py-2">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="text-lg font-bold text-foreground">{element?.customTitle || "To-Do / 긴급 지시"}</h3>
            {selectedDate && (
              <div className="mt-1 flex items-center gap-1 text-xs text-success">
                <CalendarIcon className="h-3 w-3" />
                <span className="font-semibold">{formatSelectedDate()} 할일</span>
              </div>
            )}
          </div>
          {/* 추가 버튼 - 항상 표시 */}
          <button
            onClick={() => setShowAddForm(!showAddForm)}
            className="flex items-center gap-1 rounded-lg bg-primary px-3 py-1.5 text-sm text-primary-foreground transition-colors hover:bg-primary/90"
            title="할 일 추가"
          >
            <Plus className="h-4 w-4" />
            추가
          </button>
        </div>
      </div>

      {/* 헤더 (통계, 필터) - showHeader가 false일 때만 숨김 */}
      {element?.showHeader !== false && (
        <div className="border-b border-border bg-background px-4 py-3">
          {/* 통계 */}
          {stats && (
            <div className="grid grid-cols-4 gap-2 text-xs mb-3">
              <div className="rounded bg-primary/10 px-2 py-1.5 text-center">
                <div className="font-bold text-primary">{stats.pending}</div>
                <div className="text-primary">대기</div>
              </div>
              <div className="rounded bg-warning/10 px-2 py-1.5 text-center">
                <div className="font-bold text-warning">{stats.inProgress}</div>
                <div className="text-warning">진행중</div>
              </div>
              <div className="rounded bg-destructive/10 px-2 py-1.5 text-center">
                <div className="font-bold text-destructive">{stats.urgent}</div>
                <div className="text-destructive">긴급</div>
              </div>
              <div className="rounded bg-destructive/10 px-2 py-1.5 text-center">
                <div className="font-bold text-destructive">{stats.overdue}</div>
                <div className="text-destructive">지연</div>
              </div>
            </div>
          )}

          {/* 필터 */}
          <div className="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-primary-foreground"
                    : "bg-muted text-foreground hover:bg-muted"
                }`}
              >
                {f === "all" ? "전체" : f === "pending" ? "대기" : f === "in_progress" ? "진행중" : "완료"}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 추가 폼 */}
      {showAddForm && (
        <div className="max-h-[400px] overflow-y-auto border-b border-border bg-background p-4">
          <div className="space-y-2">
            <input
              type="text"
              placeholder="할 일 제목*"
              value={newTodo.title}
              onChange={(e) => setNewTodo({ ...newTodo, title: e.target.value })}
              onKeyDown={(e) => e.stopPropagation()}
              className="w-full rounded border border-border 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 })}
              onKeyDown={(e) => e.stopPropagation()}
              className="w-full rounded border border-border 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-border 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-border 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-border"
                />
                <span className="text-destructive 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-primary-foreground hover:bg-primary/90"
              >
                추가
              </button>
              <button
                onClick={() => setShowAddForm(false)}
                className="rounded bg-muted px-4 py-2 text-sm text-foreground hover:bg-muted/90"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      )}

      {/* To-Do 리스트 */}
      <div className="flex-1 overflow-y-auto p-4 min-h-0">
        {filteredTodos.length === 0 ? (
          <div className="flex h-full items-center justify-center text-muted-foreground">
            <div className="text-center">
              <div className="mb-2 text-4xl">📝</div>
              <div>{selectedDate ? `${formatSelectedDate()} 할 일이 없습니다` : "할 일이 없습니다"}</div>
            </div>
          </div>
        ) : (
          <div className="space-y-2">
            {filteredTodos.map((todo) => (
              <div
                key={todo.id}
                className={`group relative rounded-lg border-2 bg-background p-3 shadow-sm transition-all hover:shadow-md ${
                  todo.isUrgent ? "border-destructive" : "border-border"
                } ${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-destructive">⚡</span>}
                          {todo.title}
                        </div>
                        {todo.description && (
                          <div className="mt-1 text-xs text-foreground">{todo.description}</div>
                        )}
                        {todo.dueDate && (
                          <div className="mt-1 text-xs text-muted-foreground">{getTimeRemaining(todo.dueDate)}</div>
                        )}
                      </div>

                      {/* 액션 버튼 */}
                      <div className="flex gap-1">
                        {todo.status !== "completed" && (
                          <button
                            onClick={() => handleUpdateStatus(todo.id, "completed")}
                            className="rounded p-1 text-success hover:bg-success/10"
                            title="완료"
                          >
                            <Check className="h-4 w-4" />
                          </button>
                        )}
                        <button
                          onClick={() => handleDelete(todo.id)}
                          className="rounded p-1 text-destructive hover:bg-destructive/10"
                          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-primary/10 text-primary"
                              : "bg-muted text-foreground hover:bg-muted"
                          }`}
                        >
                          대기
                        </button>
                        <button
                          onClick={() => handleUpdateStatus(todo.id, "in_progress")}
                          className={`rounded px-2 py-1 text-xs ${
                            todo.status === "in_progress"
                              ? "bg-warning/10 text-warning"
                              : "bg-muted text-foreground hover:bg-muted"
                          }`}
                        >
                          진행중
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

