"use client";

import { useEffect, useState } from "react";

import AppShell from "@/components/AppShell";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { DateTimePicker } from "@/components/ui/datetime-picker";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RecurrencePicker, type RecurrenceRule as RecurrenceRuleInput } from "@/components/ui/recurrence-picker";
import { api } from "@/lib/api";
import { useTranslation } from "@/lib/i18n";
import { Bell, CalendarCheck, CheckCircle2, ListTodo, Plus, Repeat, Trash2 } from "lucide-react";

type RecurrenceType = "hourly" | "daily" | "weekly" | "monthly" | "yearly";

type RecurrenceRule = {
  id: string;
  type: RecurrenceType;
  interval: number;
  byWeekday?: number | null;
  byMonthday?: number | null;
};

type Todo = {
  id: string;
  title: string;
  description?: string | null;
  dueAt: string;
  recurrenceRule?: RecurrenceRule | null;
  isCheckedIn: boolean;
  checkInCount: number;
  checkInAt?: string | null;
};

type ReminderTask = {
  id: string;
  title: string;
  dueAt: string;
};

const TodosPage = () => {
  const t = useTranslation();
  const [todos, setTodos] = useState<Todo[]>([]);
  const [reminders, setReminders] = useState<ReminderTask[]>([]);
  const [title, setTitle] = useState("");
  const [dueAt, setDueAt] = useState<Date | undefined>(undefined);
  const [offsetMinutes, setOffsetMinutes] = useState(10);
  const [isRecurring, setIsRecurring] = useState(false);
  const [recurrenceRule, setRecurrenceRule] = useState<RecurrenceRuleInput>({ type: "daily", interval: 1 });
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [checkingIn, setCheckingIn] = useState<string | null>(null);

  const loadTodos = async () => {
    const data = (await api.getTodos()) as Todo[];
    setTodos(data);
  };

  const loadReminders = async () => {
    const data = (await api.getReminderTasks()) as ReminderTask[];
    setReminders(data);
  };

  useEffect(() => {
    loadTodos().catch(() => null);
    loadReminders().catch(() => null);
  }, []);

  const resetForm = () => {
    setTitle("");
    setDueAt(undefined);
    setIsRecurring(false);
    setRecurrenceRule({ type: "daily", interval: 1 });
    setOffsetMinutes(10);
  };

  const createTodo = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!dueAt) return;
    await api.createTodo({
      title,
      dueAt: dueAt.toISOString(),
      offsets: [{ offsetMinutes, channelInapp: true, channelBark: true }],
      ...(isRecurring && {
        recurrenceRule: {
          type: recurrenceRule.type,
          interval: recurrenceRule.interval,
          by_weekday: recurrenceRule.byWeekday,
          by_monthday: recurrenceRule.byMonthday,
        },
      }),
    });
    resetForm();
    setIsDialogOpen(false);
    await loadTodos();
  };

  const deleteTodo = async (id: string) => {
    await api.deleteTodo(id);
    await loadTodos();
  };

  const checkInTodo = async (id: string) => {
    setCheckingIn(id);
    try {
      await api.checkInTodo(id);
      await loadTodos();
    } finally {
      setCheckingIn(null);
    }
  };

  const getRecurrenceLabel = (rule: RecurrenceRule): string => {
    const interval = rule.interval || 1;
    if (rule.type === "weekly" && interval === 2) {
      return t("modeBiweekly");
    }
    switch (rule.type) {
      case "daily": return t("modeDaily");
      case "weekly": return t("modeWeekly");
      case "monthly": return t("modeMonthly");
      case "yearly": return t("modeYearly");
      default: return rule.type;
    }
  };

  const formatDueDate = (dateStr: string): string => {
    const d = new Date(dateStr);
    const now = new Date();
    const isToday = d.toDateString() === now.toDateString();
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const isTomorrow = d.toDateString() === tomorrow.toDateString();
    const pad = (n: number) => n.toString().padStart(2, "0");
    const timeStr = `${pad(d.getHours())}:${pad(d.getMinutes())}`;

    if (isToday) return `Today ${timeStr}`;
    if (isTomorrow) return `Tomorrow ${timeStr}`;
    return `${pad(d.getMonth() + 1)}/${pad(d.getDate())} ${timeStr}`;
  };

  const getDueStatus = (dateStr: string, isCheckedIn: boolean): { label: string; className: string } => {
    if (isCheckedIn) {
      return { label: t("checkInSuccess"), className: "bg-emerald-50 text-emerald-700 border-emerald-200" };
    }
    const d = new Date(dateStr);
    const now = new Date();
    if (d < now) {
      return { label: "Overdue", className: "bg-red-50 text-red-700 border-red-200" };
    }
    const hoursUntil = (d.getTime() - now.getTime()) / (1000 * 60 * 60);
    if (hoursUntil <= 24) {
      return { label: "Due Soon", className: "bg-amber-50 text-amber-700 border-amber-200" };
    }
    return { label: "Upcoming", className: "bg-blue-50 text-blue-700 border-blue-200" };
  };

  // Stats
  const totalTasks = todos.length;
  const checkedInCount = todos.filter((t) => t.isCheckedIn).length;
  const recurringCount = todos.filter((t) => t.recurrenceRule).length;

  // Upcoming reminders (next 3, sorted by dueAt)
  const upcomingReminders = reminders
    .filter((r) => new Date(r.dueAt) >= new Date())
    .sort((a, b) => new Date(a.dueAt).getTime() - new Date(b.dueAt).getTime())
    .slice(0, 3);

  return (
    <AppShell>
      <div className="grid gap-5 lg:grid-cols-[1fr_280px]">
        {/* Left column - Todo list */}
        <Card>
          <CardHeader className="flex-row items-center justify-between space-y-0">
            <div>
              <CardTitle className="text-xl">{t("myTodoList")}</CardTitle>
              <CardDescription>{t("myTodoListDesc")}</CardDescription>
            </div>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button type="button">
                  <Plus className="h-4 w-4" />
                  {t("addTask")}
                </Button>
              </DialogTrigger>
              <DialogContent className="w-[90vw] max-w-[90vw] sm:w-[40vw] sm:max-w-[40vw]">
                <form onSubmit={createTodo}>
                  <DialogHeader>
                    <DialogTitle>{t("createTask")}</DialogTitle>
                    <DialogDescription>{t("createTaskDesc")}</DialogDescription>
                  </DialogHeader>
                  <div className="grid gap-4 py-4">
                    <div className="space-y-2">
                      <Label htmlFor="title">{t("title")}</Label>
                      <Input
                        id="title"
                        placeholder={t("enterTodoTitle")}
                        value={title}
                        onChange={(event) => setTitle(event.target.value)}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="dueAt">{t("dueTime")}</Label>
                      <DateTimePicker
                        value={dueAt}
                        onChange={setDueAt}
                        placeholder="选择截止日期和时间"
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="offset">{t("advanceReminder")}</Label>
                      <Input
                        id="offset"
                        type="number"
                        min={0}
                        value={offsetMinutes}
                        onChange={(event) => setOffsetMinutes(Number(event.target.value))}
                      />
                    </div>
                    <div className="space-y-3">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id="recurring"
                          checked={isRecurring}
                          onCheckedChange={(checked) => setIsRecurring(checked === true)}
                        />
                        <Label htmlFor="recurring">{t("setRecurring")}</Label>
                      </div>
                      {isRecurring && (
                        <div className="mt-3">
                          <RecurrencePicker
                            value={recurrenceRule}
                            onChange={setRecurrenceRule}
                            dueDate={dueAt}
                          />
                        </div>
                      )}
                    </div>
                  </div>
                  <DialogFooter>
                    <Button type="submit" disabled={!title || !dueAt}>
                      {t("save")}
                    </Button>
                  </DialogFooter>
                </form>
              </DialogContent>
            </Dialog>
          </CardHeader>
          <CardContent>
            {todos.length > 0 ? (
              <div className="divide-y divide-border/50">
                {/* Table header */}
                <div className="grid grid-cols-[auto_1fr_auto_auto_auto] items-center gap-4 px-3 pb-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                  <div className="w-5" />
                  <div>{t("title")}</div>
                  <div>{t("due")}</div>
                  <div>{t("status")}</div>
                  <div className="w-16" />
                </div>
                {todos.map((todo) => {
                  const status = getDueStatus(todo.dueAt, todo.isCheckedIn);
                  return (
                    <div
                      key={todo.id}
                      className="group grid grid-cols-[auto_1fr_auto_auto_auto] items-center gap-4 px-3 py-3 transition-colors hover:bg-muted/40 rounded-lg"
                    >
                      {/* Checkbox / Check-in */}
                      <button
                        type="button"
                        className={`flex h-5 w-5 items-center justify-center rounded-full border-2 transition-colors ${
                          todo.isCheckedIn
                            ? "border-emerald-500 bg-emerald-500 text-white"
                            : "border-border hover:border-emerald-400"
                        }`}
                        onClick={() => checkInTodo(todo.id)}
                        disabled={checkingIn === todo.id || todo.isCheckedIn}
                      >
                        {todo.isCheckedIn && <CheckCircle2 className="h-3 w-3" />}
                      </button>

                      {/* Title + badges */}
                      <div className="min-w-0">
                        <div className="flex items-center gap-2">
                          <span className={`truncate text-sm font-medium ${todo.isCheckedIn ? "text-muted-foreground line-through" : "text-foreground"}`}>
                            {todo.title}
                          </span>
                          {todo.recurrenceRule && (
                            <span className="inline-flex items-center gap-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700">
                              <Repeat className="h-3 w-3" />
                              {getRecurrenceLabel(todo.recurrenceRule)}
                            </span>
                          )}
                          {todo.checkInCount > 0 && (
                            <span className="rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium text-emerald-700">
                              {todo.checkInCount}x
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Due date */}
                      <div className="text-xs text-muted-foreground whitespace-nowrap">
                        {formatDueDate(todo.dueAt)}
                      </div>

                      {/* Status pill */}
                      <span className={`inline-flex rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap ${status.className}`}>
                        {status.label}
                      </span>

                      {/* Delete */}
                      <div className="flex justify-end w-16">
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <button
                              type="button"
                              className="rounded-lg p-1.5 text-muted-foreground opacity-0 transition-all hover:bg-red-50 hover:text-red-500 group-hover:opacity-100"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>{t("confirmDelete")}</AlertDialogTitle>
                              <AlertDialogDescription>
                                {t("confirmDeleteDesc", { title: todo.title })}
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
                              <AlertDialogAction
                                className="bg-red-500 hover:bg-red-600"
                                onClick={() => deleteTodo(todo.id)}
                              >
                                {t("delete")}
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </div>
                  );
                })}
              </div>
            ) : (
              /* Empty state */
              <div className="flex flex-col items-center justify-center py-16">
                <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                  <ListTodo className="h-7 w-7" />
                </div>
                <h3 className="mt-4 text-lg font-semibold text-foreground">{t("todoEmptyTitle")}</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{t("todoEmptyDesc")}</p>
                <Button className="mt-5" onClick={() => setIsDialogOpen(true)}>
                  <Plus className="h-4 w-4" />
                  {t("addTask")}
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Right column - Stats & Upcoming */}
        <div className="flex flex-col gap-5">
          {/* Stats cards */}
          <div className="grid grid-cols-1 gap-3">
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-primary/10 text-primary">
                  <ListTodo className="h-4 w-4" />
                </div>
                <div>
                  <div className="text-2xl font-semibold text-foreground">{totalTasks}</div>
                  <div className="text-xs text-muted-foreground">{t("totalTasks")}</div>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-emerald-500/10 text-emerald-600">
                  <CalendarCheck className="h-4 w-4" />
                </div>
                <div>
                  <div className="text-2xl font-semibold text-foreground">{checkedInCount}</div>
                  <div className="text-xs text-muted-foreground">{t("checkedInToday")}</div>
                </div>
              </div>
            </Card>
            <Card className="p-4">
              <div className="flex items-center gap-3">
                <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-blue-500/10 text-blue-600">
                  <Repeat className="h-4 w-4" />
                </div>
                <div>
                  <div className="text-2xl font-semibold text-foreground">{recurringCount}</div>
                  <div className="text-xs text-muted-foreground">{t("recurringTasks")}</div>
                </div>
              </div>
            </Card>
          </div>

          {/* Upcoming reminders */}
          <Card>
            <CardHeader className="p-4 pb-3">
              <CardTitle className="text-[15px] font-semibold">{t("upcomingReminders")}</CardTitle>
            </CardHeader>
            <CardContent className="p-4 pt-0">
              {upcomingReminders.length > 0 ? (
                <div className="space-y-2.5">
                  {upcomingReminders.map((reminder) => (
                    <div key={reminder.id} className="flex items-start gap-2.5">
                      <div className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600">
                        <Bell className="h-3.5 w-3.5" />
                      </div>
                      <div className="min-w-0">
                        <div className="truncate text-sm font-medium text-foreground">{reminder.title}</div>
                        <div className="text-xs text-muted-foreground">{formatDueDate(reminder.dueAt)}</div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-xs text-muted-foreground">{t("noUpcomingReminders")}</p>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </AppShell>
  );
};

export default TodosPage;
