"use client";

import { useEffect, useState } from "react";

import AppShell from "@/components/AppShell";
import Avatar from "@/components/ui/avatar";
import { X } from "lucide-react";

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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { RecurrencePicker, type RecurrenceRule as RecurrenceRuleInput } from "@/components/ui/recurrence-picker";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { api } from "@/lib/api";
import { useTranslation } from "@/lib/i18n";

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

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

type User = { id: string; username: string; avatar?: string | null };
type Task = { id: string; title: string; dueAt: string; recurrenceRule?: RecurrenceRule | null };

const RemindersPage = () => {
  const t = useTranslation();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [users, setUsers] = useState<User[]>([]);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [dueAt, setDueAt] = useState<Date | undefined>(undefined);
  const [offsetMinutes, setOffsetMinutes] = useState(0);
  const [showAdvanceReminder, setShowAdvanceReminder] = useState(false);
  const [recipientIds, setRecipientIds] = useState<string[]>([]);
  const [isRecurring, setIsRecurring] = useState(false);
  const [recurrenceRule, setRecurrenceRule] = useState<RecurrenceRuleInput>({ type: "daily", interval: 1 });

  // Bark settings
  const [showBarkSettings, setShowBarkSettings] = useState(false);
  const [barkTitle, setBarkTitle] = useState("");
  const [barkSubtitle, setBarkSubtitle] = useState("");
  const [barkUseMarkdown, setBarkUseMarkdown] = useState(false);
  const [barkMarkdownContent, setBarkMarkdownContent] = useState("");
  const [barkLevel, setBarkLevel] = useState<string>("");
  const [barkIcon, setBarkIcon] = useState("");

  const load = async () => {
    const [tasksData, usersData] = await Promise.all([api.getReminderTasks(), api.getUsers()]);
    setTasks(tasksData as Task[]);
    setUsers(usersData as User[]);
  };

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

  const addRecipient = (id: string) => {
    setRecipientIds((prev) => (prev.includes(id) ? prev : [...prev, id]));
  };

  const removeRecipient = (id: string) => {
    setRecipientIds((prev) => prev.filter((item) => item !== id));
  };

  const createTask = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!dueAt || recipientIds.length === 0) return;
    await api.createReminderTask({
      title,
      content: barkUseMarkdown && barkMarkdownContent ? barkMarkdownContent : content,
      dueAt: dueAt.toISOString(),
      recipientIds,
      offsets: [{
        offsetMinutes,
        channelInapp: true,
        channelBark: true,
        ...(barkTitle && { barkTitle }),
        ...(barkSubtitle && { barkSubtitle }),
        ...(barkUseMarkdown && barkMarkdownContent && { barkBodyMarkdown: barkMarkdownContent }),
        ...(barkLevel && { barkLevel }),
        ...(barkIcon && { barkIcon }),
      }],
      ...(isRecurring && {
        recurrenceRule: {
          type: recurrenceRule.type,
          interval: recurrenceRule.interval,
          by_weekday: recurrenceRule.byWeekday,
          by_monthday: recurrenceRule.byMonthday,
        },
      }),
    });
    setTitle("");
    setContent("");
    setDueAt(undefined);
    setOffsetMinutes(0);
    setShowAdvanceReminder(false);
    setRecipientIds([]);
    setIsRecurring(false);
    setRecurrenceRule({ type: "daily", interval: 1 });
    // Reset Bark settings
    setShowBarkSettings(false);
    setBarkTitle("");
    setBarkSubtitle("");
    setBarkUseMarkdown(false);
    setBarkMarkdownContent("");
    setBarkLevel("");
    setBarkIcon("");
    await load();
  };

  const deleteTask = async (id: string) => {
    await api.deleteReminderTask(id);
    await load();
  };

  const formatDateTime = (dateStr: string): string => {
    const d = new Date(dateStr);
    const pad = (n: number) => n.toString().padStart(2, "0");
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
  };

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

  return (
    <AppShell>
      <div>
        <h1 className="text-xl font-semibold tracking-tight text-foreground">{t("navReminder")}</h1>
        <p className="mt-1 text-sm text-muted-foreground">{t("createReminderDesc")}</p>
      </div>
      <div className="grid gap-6 lg:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>{t("createReminder")}</CardTitle>
            <CardDescription>{t("createReminderDesc")}</CardDescription>
          </CardHeader>
          <CardContent>
            <form className="space-y-4" onSubmit={createTask}>
              <div className="space-y-2">
                <Label htmlFor="title">{t("taskTitle")}</Label>
                <Input
                  id="title"
                  placeholder={t("enterTaskTitle")}
                  value={title}
                  onChange={(event) => setTitle(event.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="content">{t("reminderContent")}</Label>
                <textarea
                  id="content"
                  className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                  placeholder={t("enterReminderContent")}
                  value={content}
                  onChange={(event) => setContent(event.target.value)}
                  disabled={barkUseMarkdown && !!barkMarkdownContent}
                />
                {barkUseMarkdown && barkMarkdownContent && (
                  <p className="text-xs text-amber-600">{t("contentReplacedByMarkdown")}</p>
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="dueAt">
                  {t("reminderTime")}
                  <span className="ml-1 text-red-500">*</span>
                </Label>
                <DateTimePicker
                  value={dueAt}
                  onChange={setDueAt}
                  placeholder={t("selectReminderTime")}
                />
              </div>
              <div className="space-y-3">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="showAdvanceReminder"
                    checked={showAdvanceReminder}
                    onCheckedChange={(checked) => {
                      setShowAdvanceReminder(checked === true);
                      if (!checked) setOffsetMinutes(0);
                    }}
                  />
                  <Label htmlFor="showAdvanceReminder">{t("enableAdvanceReminder")}</Label>
                </div>
                {showAdvanceReminder && (
                  <div className="ml-6 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>
              <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("setRecurringReminder")}</Label>
                </div>
                {isRecurring && (
                  <div className="mt-3">
                    <RecurrencePicker
                      value={recurrenceRule}
                      onChange={setRecurrenceRule}
                      dueDate={dueAt}
                    />
                  </div>
                )}
              </div>
              <div className="space-y-3">
                <Label>
                  {t("reminderFor")}
                  <span className="ml-1 text-red-500">*</span>
                </Label>
                <Select
                  value=""
                  onValueChange={(value) => addRecipient(value)}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder={t("selectUser")} />
                  </SelectTrigger>
                  <SelectContent>
                    {users
                      .filter((user) => !recipientIds.includes(user.id))
                      .map((user) => (
                        <SelectItem key={user.id} value={user.id}>
                          <div className="flex items-center gap-2">
                            <Avatar username={user.username} src={user.avatar} size="sm" className="h-5 w-5 text-xs" />
                            <span>{user.username}</span>
                          </div>
                        </SelectItem>
                      ))}
                  </SelectContent>
                </Select>
                {recipientIds.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {recipientIds.map((id) => {
                      const user = users.find((u) => u.id === id);
                      if (!user) return null;
                      return (
                        <span
                          key={id}
                          className="inline-flex items-center gap-1.5 rounded-full bg-muted px-2 py-1 text-sm text-foreground/80"
                        >
                          <Avatar username={user.username} src={user.avatar} size="sm" className="h-5 w-5 text-xs" />
                          {user.username}
                          <button
                            type="button"
                            onClick={() => removeRecipient(id)}
                            className="rounded-full p-0.5 hover:bg-muted/80"
                          >
                            <X className="h-3 w-3" />
                          </button>
                        </span>
                      );
                    })}
                  </div>
                )}
              </div>
              {/* Bark Settings */}
              <div className="space-y-3">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="showBarkSettings"
                    checked={showBarkSettings}
                    onCheckedChange={(checked) => setShowBarkSettings(checked === true)}
                  />
                  <Label htmlFor="showBarkSettings">{t("barkSettings")}</Label>
                </div>
                {showBarkSettings && (
                  <div className="ml-6 space-y-4 rounded-xl border border-border/60 bg-muted/30 p-4">
                    <p className="text-sm text-muted-foreground">{t("barkSettingsDesc")}</p>
                    
                    <div className="space-y-2">
                      <Label htmlFor="barkTitle">{t("barkTitle")}</Label>
                      <Input
                        id="barkTitle"
                        placeholder={t("barkTitlePlaceholder")}
                        value={barkTitle}
                        onChange={(e) => setBarkTitle(e.target.value)}
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="barkSubtitle">{t("barkSubtitle")}</Label>
                      <Input
                        id="barkSubtitle"
                        placeholder={t("barkSubtitlePlaceholder")}
                        value={barkSubtitle}
                        onChange={(e) => setBarkSubtitle(e.target.value)}
                      />
                    </div>

                    <div className="space-y-3">
                      <div className="flex items-center space-x-2">
                        <Checkbox
                          id="barkUseMarkdown"
                          checked={barkUseMarkdown}
                          onCheckedChange={(checked) => setBarkUseMarkdown(checked === true)}
                        />
                        <Label htmlFor="barkUseMarkdown">{t("barkUseMarkdown")}</Label>
                      </div>
                      {barkUseMarkdown && (
                        <div className="space-y-2">
                          <p className="text-xs text-amber-600">{t("markdownWillReplaceContent")}</p>
                          <Label htmlFor="barkMarkdown">{t("barkMarkdownContent")}</Label>
                          <textarea
                            id="barkMarkdown"
                            className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                            placeholder={t("barkMarkdownPlaceholder")}
                            value={barkMarkdownContent}
                            onChange={(e) => setBarkMarkdownContent(e.target.value)}
                          />
                        </div>
                      )}
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="barkLevel">{t("barkLevel")}</Label>
                      <Select value={barkLevel} onValueChange={setBarkLevel}>
                        <SelectTrigger>
                          <SelectValue placeholder={t("barkLevelActive")} />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="active">{t("barkLevelActive")}</SelectItem>
                          <SelectItem value="timeSensitive">{t("barkLevelTimeSensitive")}</SelectItem>
                          <SelectItem value="passive">{t("barkLevelPassive")}</SelectItem>
                          <SelectItem value="critical">{t("barkLevelCritical")}</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="barkIcon">{t("barkIcon")}</Label>
                      <Input
                        id="barkIcon"
                        placeholder={t("barkIconPlaceholder")}
                        value={barkIcon}
                        onChange={(e) => setBarkIcon(e.target.value)}
                      />
                    </div>
                  </div>
                )}
              </div>

              <div className="flex items-center gap-3">
                <Button type="submit" disabled={!dueAt || recipientIds.length === 0}>
                  {t("save")}
                </Button>
                <Button type="button" variant="outline">
                  {t("cancel")}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>{t("reminderList")}</CardTitle>
            <CardDescription>{t("reminderListDesc")}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid gap-3">
              {tasks.map((task) => (
                <div
                  key={task.id}
                  className="flex items-center justify-between rounded-xl bg-muted/50 px-4 py-3 transition-colors hover:bg-muted"
                >
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-semibold text-foreground">{task.title}</span>
                      {task.recurrenceRule && (
                        <span className="rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700">
                          {getRecurrenceLabel(task.recurrenceRule)}
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-muted-foreground">
                      {formatDateTime(task.dueAt)}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-medium text-muted-foreground">{t("reminder")}</span>
                    <AlertDialog>
                      <AlertDialogTrigger asChild>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="text-muted-foreground hover:text-red-500"
                        >
                          {t("delete")}
                        </Button>
                      </AlertDialogTrigger>
                      <AlertDialogContent>
                        <AlertDialogHeader>
                          <AlertDialogTitle>{t("confirmDelete")}</AlertDialogTitle>
                          <AlertDialogDescription>
                            {t("confirmDeleteDesc", { title: task.title })}
                          </AlertDialogDescription>
                        </AlertDialogHeader>
                        <AlertDialogFooter>
                          <AlertDialogCancel>{t("cancel")}</AlertDialogCancel>
                          <AlertDialogAction
                            className="bg-red-500 hover:bg-red-600"
                            onClick={() => deleteTask(task.id)}
                          >
                            {t("delete")}
                          </AlertDialogAction>
                        </AlertDialogFooter>
                      </AlertDialogContent>
                    </AlertDialog>
                  </div>
                </div>
              ))}
              {tasks.length === 0 && (
                <div className="rounded-xl bg-muted/50 p-6 text-center text-sm text-muted-foreground">
                  {t("noReminder")}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </AppShell>
  );
};

export default RemindersPage;
