import { useCallback, useState } from "react";
import { Bell, BellOff, MoonStar } from "lucide-react";
import { api } from "@/client";
import { Button } from "@/components/ui/button";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Slider } from "@/components/ui/slider";
import { cn } from "@/lib/utils";

type DndState = {
  do_not_disturb: boolean;
  dnd_start_hour?: number;
  dnd_end_hour?: number;
};

type Props = {
  roomId: string;
};

export default function RoomDndToggle({ roomId }: Props) {
  const [dnd, setDnd] = useState<DndState>({ do_not_disturb: false });
  const [loading, setLoading] = useState(false);

  const toggle = useCallback(async () => {
    setLoading(true);
    const next = !dnd.do_not_disturb;
    try {
      await api.patch(`/api/v1/ws/rooms/${roomId}/dnd`, {
        do_not_disturb: next,
        dnd_start_hour: dnd.dnd_start_hour ?? 22,
        dnd_end_hour: dnd.dnd_end_hour ?? 7,
      });
      setDnd((prev) => ({ ...prev, do_not_disturb: next }));
    } finally {
      setLoading(false);
    }
  }, [dnd.do_not_disturb, dnd.dnd_start_hour, dnd.dnd_end_hour, roomId]);

  const formatHour = (h: number) => {
    const period = h >= 12 ? "PM" : "AM";
    const hour = h % 12 || 12;
    return `${hour} ${period}`;
  };

  return (
    <Popover>
      <PopoverTrigger>
        <Button
          className={cn(
            "size-8 cursor-pointer rounded-lg transition-[background-color,border-color,color,opacity,box-shadow,transform] duration-150",
            dnd.do_not_disturb
              ? "text-warning hover:bg-accent/40"
              : "text-muted-foreground/40 hover:bg-accent/40 hover:text-muted-foreground",
          )}
          size="icon"
          title={
            dnd.do_not_disturb ? "Do Not Disturb ON" : "Do Not Disturb OFF"
          }
          variant="ghost"
        >
          {dnd.do_not_disturb ? (
            <BellOff className="size-[18px]" />
          ) : (
            <Bell className="size-[18px]" />
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-64" side="bottom">
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-semibold text-foreground">
                Do Not Disturb
              </p>
              <p className="text-[11px] text-muted-foreground/40">
                {dnd.do_not_disturb
                  ? "Notifications are muted"
                  : "Notifications are on"}
              </p>
            </div>
            <Button
              className="cursor-pointer rounded-lg"
              disabled={loading}
              onClick={toggle}
              size="sm"
              variant={dnd.do_not_disturb ? "default" : "outline"}
            >
              {dnd.do_not_disturb ? "Turn Off" : "Turn On"}
            </Button>
          </div>

          {dnd.do_not_disturb && (
            <div className="space-y-3 rounded-lg bg-muted/20 p-3">
              <div className="flex items-center gap-2 text-[11px] text-muted-foreground/50">
                <MoonStar className="size-3.5 text-indigo-400/70" />
                <span>
                  Quiet hours: {formatHour(dnd.dnd_start_hour ?? 22)} –{" "}
                  {formatHour(dnd.dnd_end_hour ?? 7)}
                </span>
              </div>
              <div className="flex gap-3">
                <div className="flex-1 space-y-1.5">
                  <label className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/40">
                    Start
                  </label>
                  <Slider
                    defaultValue={[dnd.dnd_start_hour ?? 22]}
                    max={23}
                    min={0}
                    onValueChange={(val) =>
                      setDnd((prev) => ({
                        ...prev,
                        dnd_start_hour: Array.isArray(val) ? val[0] : val,
                      }))
                    }
                    step={1}
                  />
                </div>
                <div className="flex-1 space-y-1.5">
                  <label className="text-[10px] font-medium uppercase tracking-wider text-muted-foreground/40">
                    End
                  </label>
                  <Slider
                    defaultValue={[dnd.dnd_end_hour ?? 7]}
                    max={23}
                    min={0}
                    onValueChange={(val) =>
                      setDnd((prev) => ({
                        ...prev,
                        dnd_end_hour: Array.isArray(val) ? val[0] : val,
                      }))
                    }
                    step={1}
                  />
                </div>
              </div>
            </div>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}
