import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { toast } from "sonner";
import { useState, useEffect, useCallback, useMemo } from "react";
import {
  Bell, BellRing, Plus, Trash2, Clock, Calendar,
  CheckCircle2, XCircle, Settings, BellOff, Volume2
} from "lucide-react";

const DAY_NAMES = ["日", "一", "二", "三", "四", "五", "六"];

const REMINDER_TYPES = [
  { value: "training", label: "训练提醒", icon: <Clock className="w-4 h-4" /> },
  { value: "checkin", label: "打卡提醒", icon: <CheckCircle2 className="w-4 h-4" /> },
  { value: "analysis", label: "分析提醒", icon: <Settings className="w-4 h-4" /> },
];

export default function Reminders() {
  const { user } = useAuth();
  const [showCreate, setShowCreate] = useState(false);
  const [newReminder, setNewReminder] = useState({
    reminderType: "training",
    title: "",
    message: "",
    timeOfDay: "08:00",
    daysOfWeek: [1, 2, 3, 4, 5] as number[],
  });

  const utils = trpc.useUtils();
  const { data: reminders, isLoading } = trpc.reminder.list.useQuery(undefined, { enabled: !!user });
  const { data: notifications } = trpc.notification.list.useQuery(undefined, { enabled: !!user });
  const { data: unreadCount } = trpc.notification.unreadCount.useQuery(undefined, { enabled: !!user });

  const createReminder = trpc.reminder.create.useMutation({
    onSuccess: () => {
      toast.success("提醒已创建");
      setShowCreate(false);
      setNewReminder({ reminderType: "training", title: "", message: "", timeOfDay: "08:00", daysOfWeek: [1, 2, 3, 4, 5] });
      utils.reminder.list.invalidate();
    },
  });

  const deleteReminder = trpc.reminder.delete.useMutation({
    onSuccess: () => {
      toast.success("提醒已删除");
      utils.reminder.list.invalidate();
    },
  });

  const toggleReminder = trpc.reminder.toggle.useMutation({
    onSuccess: () => {
      utils.reminder.list.invalidate();
    },
  });

  const markAllRead = trpc.notification.markAllRead.useMutation({
    onSuccess: () => {
      utils.notification.list.invalidate();
      utils.notification.unreadCount.invalidate();
      toast.success("全部已读");
    },
  });

  const markRead = trpc.notification.markRead.useMutation({
    onSuccess: () => {
      utils.notification.list.invalidate();
      utils.notification.unreadCount.invalidate();
    },
  });

  const toggleDay = useCallback((day: number) => {
    setNewReminder(prev => ({
      ...prev,
      daysOfWeek: prev.daysOfWeek.includes(day)
        ? prev.daysOfWeek.filter(d => d !== day)
        : [...prev.daysOfWeek, day].sort(),
    }));
  }, []);

  const handleCreate = () => {
    if (!newReminder.title.trim()) {
      toast.error("请输入提醒标题");
      return;
    }
    if (newReminder.daysOfWeek.length === 0) {
      toast.error("请至少选择一天");
      return;
    }
    createReminder.mutate(newReminder);
  };

  // Browser notification permission
  const [notifPermission, setNotifPermission] = useState<NotificationPermission>("default");

  useEffect(() => {
    if ("Notification" in window) {
      setNotifPermission(Notification.permission);
    }
  }, []);

  const requestPermission = async () => {
    if ("Notification" in window) {
      const perm = await Notification.requestPermission();
      setNotifPermission(perm);
      if (perm === "granted") {
        toast.success("通知权限已开启");
        new Notification("Tennis Training Hub", { body: "训练提醒已开启！" });
      }
    }
  };

  // Check reminders and trigger browser notifications
  useEffect(() => {
    if (!reminders || notifPermission !== "granted") return;

    const checkInterval = setInterval(() => {
      const now = new Date();
      const currentTime = `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
      const currentDay = now.getDay();

      reminders.forEach((r: any) => {
        if (r.isActive && r.timeOfDay === currentTime) {
          const days = typeof r.daysOfWeek === "string" ? JSON.parse(r.daysOfWeek) : r.daysOfWeek;
          if (Array.isArray(days) && days.includes(currentDay)) {
            new Notification(r.title, {
              body: r.message || "该训练了！",
              icon: "/favicon.ico",
            });
          }
        }
      });
    }, 60000); // Check every minute

    return () => clearInterval(checkInterval);
  }, [reminders, notifPermission]);

  const activeReminders = useMemo(() => reminders?.filter((r: any) => r.isActive) || [], [reminders]);
  const inactiveReminders = useMemo(() => reminders?.filter((r: any) => !r.isActive) || [], [reminders]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Bell className="w-6 h-6 text-primary" />
            训练提醒
          </h1>
          <p className="text-muted-foreground mt-1">设置定时提醒，保持训练节奏</p>
        </div>
        <div className="flex gap-2">
          {notifPermission !== "granted" && (
            <Button variant="outline" size="sm" onClick={requestPermission} className="gap-1">
              <Volume2 className="w-4 h-4" />
              开启通知
            </Button>
          )}
          <Dialog open={showCreate} onOpenChange={setShowCreate}>
            <DialogTrigger asChild>
              <Button size="sm" className="gap-1">
                <Plus className="w-4 h-4" />
                新建提醒
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>创建训练提醒</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label>提醒类型</Label>
                  <Select value={newReminder.reminderType} onValueChange={v => setNewReminder(p => ({ ...p, reminderType: v }))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {REMINDER_TYPES.map(t => (
                        <SelectItem key={t.value} value={t.value}>
                          <span className="flex items-center gap-2">{t.icon} {t.label}</span>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>标题</Label>
                  <Input
                    placeholder="例：每日正手练习"
                    value={newReminder.title}
                    onChange={e => setNewReminder(p => ({ ...p, title: e.target.value }))}
                  />
                </div>
                <div>
                  <Label>提醒内容（可选）</Label>
                  <Textarea
                    placeholder="例：记得做10分钟影子挥拍..."
                    value={newReminder.message}
                    onChange={e => setNewReminder(p => ({ ...p, message: e.target.value }))}
                    rows={2}
                  />
                </div>
                <div>
                  <Label>提醒时间</Label>
                  <Input
                    type="time"
                    value={newReminder.timeOfDay}
                    onChange={e => setNewReminder(p => ({ ...p, timeOfDay: e.target.value }))}
                  />
                </div>
                <div>
                  <Label>重复日期</Label>
                  <div className="flex gap-1.5 mt-1.5">
                    {DAY_NAMES.map((name, i) => (
                      <button
                        key={i}
                        onClick={() => toggleDay(i)}
                        className={`w-9 h-9 rounded-full text-sm font-medium transition-colors ${
                          newReminder.daysOfWeek.includes(i)
                            ? "bg-primary text-primary-foreground"
                            : "bg-muted text-muted-foreground hover:bg-muted/80"
                        }`}
                      >
                        {name}
                      </button>
                    ))}
                  </div>
                  <div className="flex gap-2 mt-2">
                    <Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [1, 2, 3, 4, 5] }))}>
                      工作日
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [0, 6] }))}>
                      周末
                    </Button>
                    <Button variant="ghost" size="sm" onClick={() => setNewReminder(p => ({ ...p, daysOfWeek: [0, 1, 2, 3, 4, 5, 6] }))}>
                      每天
                    </Button>
                  </div>
                </div>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setShowCreate(false)}>取消</Button>
                <Button onClick={handleCreate} disabled={createReminder.isPending}>
                  {createReminder.isPending ? "创建中..." : "创建"}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Notification Permission Banner */}
      {notifPermission === "default" && (
        <Card className="border-amber-200 bg-amber-50">
          <CardContent className="pt-4 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <BellRing className="w-5 h-5 text-amber-600" />
              <div>
                <p className="font-medium text-amber-900">开启浏览器通知</p>
                <p className="text-sm text-amber-700">允许通知后，到达设定时间时会收到提醒</p>
              </div>
            </div>
            <Button size="sm" onClick={requestPermission}>允许通知</Button>
          </CardContent>
        </Card>
      )}

      {notifPermission === "denied" && (
        <Card className="border-red-200 bg-red-50">
          <CardContent className="pt-4 flex items-center gap-3">
            <BellOff className="w-5 h-5 text-red-600" />
            <div>
              <p className="font-medium text-red-900">通知已被禁用</p>
              <p className="text-sm text-red-700">请在浏览器设置中手动开启本站通知权限</p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Active Reminders */}
      <div>
        <h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
          <BellRing className="w-5 h-5 text-green-600" />
          活跃提醒 ({activeReminders.length})
        </h2>
        {activeReminders.length === 0 ? (
          <Card>
            <CardContent className="pt-6 text-center text-muted-foreground">
              <Bell className="w-10 h-10 mx-auto mb-2 opacity-50" />
              <p>暂无活跃提醒，点击"新建提醒"开始</p>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {activeReminders.map((reminder: any) => {
              const days = typeof reminder.daysOfWeek === "string" ? JSON.parse(reminder.daysOfWeek) : reminder.daysOfWeek;
              const type = REMINDER_TYPES.find(t => t.value === reminder.reminderType);
              return (
                <Card key={reminder.id} className="hover:shadow-sm transition-shadow">
                  <CardContent className="pt-4">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          {type?.icon}
                          <span className="font-medium">{reminder.title}</span>
                        </div>
                        {reminder.message && (
                          <p className="text-sm text-muted-foreground mb-2">{reminder.message}</p>
                        )}
                        <div className="flex items-center gap-3 text-sm">
                          <span className="flex items-center gap-1 text-primary font-mono">
                            <Clock className="w-3.5 h-3.5" />
                            {reminder.timeOfDay}
                          </span>
                          <div className="flex gap-0.5">
                            {DAY_NAMES.map((name, i) => (
                              <span
                                key={i}
                                className={`w-5 h-5 rounded-full text-xs flex items-center justify-center ${
                                  Array.isArray(days) && days.includes(i)
                                    ? "bg-primary/10 text-primary font-medium"
                                    : "text-muted-foreground/40"
                                }`}
                              >
                                {name}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2 ml-2">
                        <Switch
                          checked={!!reminder.isActive}
                          onCheckedChange={checked => toggleReminder.mutate({ reminderId: reminder.id, isActive: checked ? 1 : 0 })}
                        />
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive hover:text-destructive"
                          onClick={() => deleteReminder.mutate({ reminderId: reminder.id })}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        )}
      </div>

      {/* Inactive Reminders */}
      {inactiveReminders.length > 0 && (
        <div>
          <h2 className="text-lg font-semibold mb-3 flex items-center gap-2">
            <BellOff className="w-5 h-5 text-muted-foreground" />
            已暂停 ({inactiveReminders.length})
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {inactiveReminders.map((reminder: any) => {
              const days = typeof reminder.daysOfWeek === "string" ? JSON.parse(reminder.daysOfWeek) : reminder.daysOfWeek;
              return (
                <Card key={reminder.id} className="opacity-60">
                  <CardContent className="pt-4">
                    <div className="flex items-start justify-between">
                      <div>
                        <span className="font-medium">{reminder.title}</span>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground mt-1">
                          <Clock className="w-3.5 h-3.5" />
                          {reminder.timeOfDay}
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <Switch
                          checked={false}
                          onCheckedChange={checked => toggleReminder.mutate({ reminderId: reminder.id, isActive: checked ? 1 : 0 })}
                        />
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive hover:text-destructive"
                          onClick={() => deleteReminder.mutate({ reminderId: reminder.id })}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>
        </div>
      )}

      <Separator />

      {/* Notification History */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-lg font-semibold flex items-center gap-2">
            <Calendar className="w-5 h-5" />
            通知记录
            {(unreadCount as number) > 0 && (
              <Badge variant="destructive" className="ml-1">{unreadCount as number}</Badge>
            )}
          </h2>
          {(unreadCount as number) > 0 && (
            <Button variant="ghost" size="sm" onClick={() => markAllRead.mutate()}>
              全部已读
            </Button>
          )}
        </div>
        <ScrollArea className="h-[300px]">
          {(!notifications || notifications.length === 0) ? (
            <div className="text-center py-8 text-muted-foreground">
              <Bell className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>暂无通知记录</p>
            </div>
          ) : (
            <div className="space-y-2">
              {notifications.map((notif: any) => (
                <div
                  key={notif.id}
                  className={`p-3 rounded-lg border transition-colors cursor-pointer ${
                    notif.isRead ? "bg-background" : "bg-blue-50 border-blue-200"
                  }`}
                  onClick={() => !notif.isRead && markRead.mutate({ notificationId: notif.id })}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-2">
                      {notif.isRead ? (
                        <CheckCircle2 className="w-4 h-4 text-muted-foreground mt-0.5" />
                      ) : (
                        <BellRing className="w-4 h-4 text-blue-600 mt-0.5" />
                      )}
                      <div>
                        <p className={`text-sm ${notif.isRead ? "" : "font-medium"}`}>{notif.title}</p>
                        {notif.message && <p className="text-xs text-muted-foreground mt-0.5">{notif.message}</p>}
                      </div>
                    </div>
                    <span className="text-xs text-muted-foreground whitespace-nowrap ml-2">
                      {new Date(notif.createdAt).toLocaleString("zh-CN", { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </ScrollArea>
      </div>
    </div>
  );
}
