import { useEffect, useState } from "react";
import {
  AlertCircle,
  Calendar,
  CalendarClock,
  CheckCircle2,
  Clock,
  Inbox,
  Loader2,
} from "lucide-react";
import DeadlineBadge from "@/components/DeadlineBadge";

// ─── Types ────────────────────────────────────────────────────────────────────

interface Memo {
  id: string;
  content: string;
  deadline?: string;
  deadline_status?: string;
  priority?: string;
  is_completed?: boolean;
  tags?: string[];
}

interface DeadlineList {
  overdue: Memo[];
  today: Memo[];
  upcoming: Memo[];
  no_date: Memo[];
  total: number;
}

import { getAccessToken } from "@/auth-state";

// ─── API fetch ────────────────────────────────────────────────────────────────

async function fetchDeadlines(): Promise<DeadlineList> {
  const token = getAccessToken();
  const res = await fetch("/api/v1/memos/deadlines", {
    headers: token ? { "Authorization": `Bearer ${token}` } : {}
  });
  if (!res.ok) throw new Error("Failed to fetch deadlines");
  return res.json();
}

async function completeMemo(memoId: string, done: boolean) {
  const token = getAccessToken();
  await fetch(`/api/v1/memos/${memoId}/complete?done=${done}`, {
    method: "PATCH",
    headers: token ? { "Authorization": `Bearer ${token}` } : {}
  });
}

// ─── Section component ────────────────────────────────────────────────────────

interface SectionProps {
  title: string;
  icon: React.ReactNode;
  color: string;
  memos: Memo[];
  onToggle: (id: string, current: boolean) => void;
  emptyText: string;
}

function Section({ title, icon, color, memos, onToggle, emptyText }: SectionProps) {
  return (
    <div className="deadline-section">
      <div className="deadline-section__header" style={{ color }}>
        {icon}
        <span>{title}</span>
        <span className="deadline-section__count">{memos.length}</span>
      </div>

      {memos.length === 0 ? (
        <p className="deadline-section__empty">{emptyText}</p>
      ) : (
        <div className="deadline-section__list">
          {memos.map((memo) => (
            <MemoDeadlineCard
              key={memo.id}
              memo={memo}
              onToggle={onToggle}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// ─── Single card ──────────────────────────────────────────────────────────────

function MemoDeadlineCard({
  memo,
  onToggle,
}: {
  memo: Memo;
  onToggle: (id: string, current: boolean) => void;
}) {
  // Extract first line as title
  const firstLine = memo.content.split("\n")[0].replace(/^#+\s*/, "").slice(0, 80);

  return (
    <div
      className={`memo-deadline-card ${memo.is_completed ? "memo-deadline-card--done" : ""} ${memo.deadline_status === "OVERDUE" ? "memo-deadline-card--overdue" : ""}`}
    >
      <button
        className="memo-deadline-card__check"
        onClick={() => onToggle(memo.id, memo.is_completed ?? false)}
        title={memo.is_completed ? "Đánh dấu chưa xong" : "Đánh dấu hoàn thành"}
      >
        <CheckCircle2
          size={20}
          style={{
            color: memo.is_completed ? "#16a34a" : "#d1d5db",
            transition: "color 0.2s",
          }}
        />
      </button>

      <div className="memo-deadline-card__body">
        <p
          className="memo-deadline-card__title"
          style={{ textDecoration: memo.is_completed ? "line-through" : "none" }}
        >
          {firstLine || "(Không có tiêu đề)"}
        </p>

        <DeadlineBadge
          deadline={memo.deadline}
          deadlineStatus={memo.deadline_status}
          priority={memo.priority}
          isCompleted={memo.is_completed}
          compact
        />

        {memo.tags && memo.tags.length > 0 && (
          <div className="memo-deadline-card__tags">
            {memo.tags.map((tag) => (
              <span key={tag} className="memo-deadline-card__tag">
                #{tag}
              </span>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────

export default function Deadlines() {
  const [data, setData] = useState<DeadlineList | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    setLoading(true);
    try {
      const result = await fetchDeadlines();
      setData(result);
    } catch (err) {
      setError("Không thể tải dữ liệu deadline.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const handleToggle = async (memoId: string, currentDone: boolean) => {
    // Optimistic update
    if (!data) return;
    const toggleMemo = (list: Memo[]) =>
      list.map((m) =>
        m.id === memoId
          ? {
              ...m,
              is_completed: !currentDone,
              deadline_status: !currentDone ? "DONE" : "PENDING",
            }
          : m
      );
    setData({
      ...data,
      overdue: toggleMemo(data.overdue),
      today: toggleMemo(data.today),
      upcoming: toggleMemo(data.upcoming),
      no_date: toggleMemo(data.no_date),
    });
    await completeMemo(memoId, !currentDone);
    // Reload for accuracy
    load();
  };

  if (loading) {
    return (
      <div className="deadlines-loading">
        <Loader2 size={32} className="animate-spin" />
        <span>Đang tải deadline...</span>
      </div>
    );
  }

  if (error) {
    return <div className="deadlines-error">{error}</div>;
  }

  const total = data?.total ?? 0;

  return (
    <div className="deadlines-page">
      {/* Header */}
      <div className="deadlines-header">
        <div className="deadlines-header__title">
          <CalendarClock size={24} />
          <h1>Deadline</h1>
        </div>
        <p className="deadlines-header__sub">
          {total > 0 ? `${total} task cần xử lý` : "Không có deadline nào cả 🎉"}
        </p>
      </div>

      {/* Sections */}
      <div className="deadlines-sections">
        <Section
          title="Quá hạn"
          icon={<AlertCircle size={16} />}
          color="#dc2626"
          memos={data?.overdue ?? []}
          onToggle={handleToggle}
          emptyText="Không có task nào quá hạn 👌"
        />

        <Section
          title="Hôm nay"
          icon={<Clock size={16} />}
          color="#2563eb"
          memos={data?.today ?? []}
          onToggle={handleToggle}
          emptyText="Không có deadline hôm nay ✨"
        />

        <Section
          title="Sắp tới (7 ngày)"
          icon={<Calendar size={16} />}
          color="#7c3aed"
          memos={data?.upcoming ?? []}
          onToggle={handleToggle}
          emptyText="Rảnh rang cả tuần 😎"
        />

        <Section
          title="Có priority, chưa đặt deadline"
          icon={<Inbox size={16} />}
          color="#b45309"
          memos={data?.no_date ?? []}
          onToggle={handleToggle}
          emptyText=""
        />
      </div>
    </div>
  );
}
