import { useState } from "react";
import { CheckSquare, Square, AlertTriangle, Calendar } from "lucide-react";
import type { TasksResponse, Task } from "../api";

interface TasksCardProps {
  data: TasksResponse;
}

type TabKey = "private" | "sams";

const TABS: { key: TabKey; label: string }[] = [
  { key: "private", label: "Privat" },
  { key: "sams", label: "Sam's" },
];

function priorityIndicator(priority: number): { color: string; label: string } {
  if (priority <= 1) return { color: "bg-cherry", label: "Hoch" };
  if (priority <= 2) return { color: "bg-gold", label: "Mittel" };
  if (priority <= 3) return { color: "bg-azure", label: "Normal" };
  return { color: "bg-base-500", label: "Niedrig" };
}

function formatDueDate(iso: string | null): string | null {
  if (!iso) return null;
  try {
    const d = new Date(iso);
    if (isNaN(d.getTime())) return null;
    const now = new Date();
    const diffDays = Math.ceil((d.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

    if (diffDays < 0) return "Überfällig";
    if (diffDays === 0) return "Heute";
    if (diffDays === 1) return "Morgen";
    return d.toLocaleDateString("de-DE", { day: "2-digit", month: "short" });
  } catch {
    return null;
  }
}

export default function TasksCard({ data }: TasksCardProps) {
  const [activeTab, setActiveTab] = useState<TabKey>("private");

  if (!data) return null;

  if (data.error) {
    return (
      <div className="deck-card p-5 animate-fade-in">
        <div className="flex items-center gap-3 text-cherry">
          <AlertTriangle className="w-5 h-5" />
          <div>
            <p className="text-sm font-medium">Aufgaben nicht verfügbar</p>
            <p className="text-xs text-base-600 mt-0.5">Verbindung fehlgeschlagen</p>
          </div>
        </div>
      </div>
    );
  }

  const group = activeTab === "private" ? data.private : data.sams;
  const tasks = group?.open ?? [];

  return (
    <div className="deck-card p-5 animate-fade-in" data-accent="azure">
      {/* Header */}
      <div className="flex items-center gap-3 mb-4">
        <CheckSquare className="w-4 h-4 text-azure" />
        <h3 className="text-sm font-semibold text-base-900">Aufgaben</h3>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-4">
        {TABS.map((tab) => {
          const tabGroup = tab.key === "private" ? data.private : data.sams;
          const openCount = tabGroup?.open_count ?? 0;
          const isActive = activeTab === tab.key;

          return (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`tab-btn ${isActive ? "active" : ""} flex items-center gap-2`}
            >
              {tab.label}
              {openCount > 0 && (
                <span className={`text-[10px] font-bold ${
                  isActive ? "text-gold" : "text-base-500"
                }`}>
                  {openCount}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* Tasks */}
      {tasks.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-8 text-base-500">
          <CheckSquare className="w-8 h-8 mb-2 opacity-20" />
          <p className="text-xs font-mono">Alles erledigt!</p>
        </div>
      ) : (
        <div className="space-y-px max-h-80 overflow-y-auto">
          {tasks.map((task) => (
            <TaskItem key={task.id} task={task} />
          ))}
        </div>
      )}
    </div>
  );
}

function TaskItem({ task }: { task: Task }) {
  const p = priorityIndicator(task.priority);
  const due = formatDueDate(task.due_date);
  const isOverdue = due === "Überfällig";

  return (
    <div className="flex items-start gap-3 px-3 py-2.5 bg-base-100 border-l-2 border-base-300 hover:border-azure transition-colors group">
      <div className="mt-0.5 flex-shrink-0">
        {task.done ? (
          <CheckSquare className="w-4 h-4 text-azure" />
        ) : (
          <Square className="w-4 h-4 text-base-400 group-hover:text-base-600 transition-colors" />
        )}
      </div>

      <div className="flex-1 min-w-0">
        <p className={`text-sm leading-snug ${
          task.done ? "text-base-500 line-through" : "text-base-800"
        }`}>
          {task.title}
        </p>

        <div className="flex items-center gap-2 mt-1.5 flex-wrap">
          {task.project_name && (
            <span className="tag border-iris/30 text-iris bg-iris/5">
              {task.project_name}
            </span>
          )}

          {due && (
            <span className={`flex items-center gap-1 text-[10px] font-mono font-medium ${
              isOverdue ? "text-cherry" : "text-base-500"
            }`}>
              <Calendar className="w-2.5 h-2.5" />
              {due}
            </span>
          )}
        </div>
      </div>

      <div className="flex-shrink-0 mt-1.5" title={p.label}>
        <div className={`w-1.5 h-1.5 ${p.color}`} style={{ borderRadius: 0 }} />
      </div>
    </div>
  );
}
