import { useCallback, useEffect, useState } from "react";
import { Hash, Loader2, Trash2 } from "lucide-react";
import { api } from "@/client";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import type { Category } from "./channel-sidebar";

type Props = {
  roomId: string;
  roomName: string;
  topic?: string | null;
  isPrivate: boolean;
  aiEnabled?: boolean;
  categoryId?: string | null;
  categories: Category[];
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onUpdated?: () => void;
  onDeleted?: () => void;
};

export default function RoomSettingsDialog({
  roomId,
  roomName,
  topic,
  isPrivate,
  aiEnabled,
  categoryId,
  categories,
  open,
  onOpenChange,
  onUpdated,
  onDeleted,
}: Props) {
  const [name, setName] = useState(roomName);
  const [topicText, setTopicText] = useState(topic ?? "");
  const [isPublic, setIsPublic] = useState(!isPrivate);
  const [aiEnabledState, setAiEnabledState] = useState(aiEnabled ?? false);
  const [category, setCategory] = useState(categoryId ?? "");
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    setName(roomName);
    setTopicText(topic ?? "");
    setIsPublic(!isPrivate);
    setAiEnabledState(aiEnabled ?? false);
    setCategory(categoryId ?? "");
    setConfirmDelete(false);
  }, [roomName, topic, isPrivate, aiEnabled, categoryId, open]);

  const handleSave = useCallback(async () => {
    const trimmed = name.trim();
    if (!trimmed) return;
    setSaving(true);
    try {
      await api.patch(`/api/v1/ws/rooms/${roomId}`, {
        room_name: trimmed !== roomName ? trimmed : undefined,
        topic: topicText !== (topic ?? "") ? topicText || null : undefined,
        public: isPublic !== !isPrivate ? isPublic : undefined,
        category:
          (category || null) !== (categoryId ?? null)
            ? category || null
            : undefined,
        ai_enabled:
          aiEnabledState !== (aiEnabled ?? false)
            ? aiEnabledState
            : undefined,
      });
      toast({ title: "Room updated" });
      onUpdated?.();
      onOpenChange(false);
    } catch {
      toast({
        title: "Error",
        description: "Failed to update room",
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  }, [
    name,
    topicText,
    isPublic,
    aiEnabledState,
    aiEnabled,
    category,
    roomId,
    roomName,
    topic,
    isPrivate,
    categoryId,
    toast,
    onUpdated,
    onOpenChange,
  ]);

  const handleDelete = useCallback(async () => {
    if (!confirmDelete) {
      setConfirmDelete(true);
      return;
    }
    setDeleting(true);
    try {
      await api.delete(`/api/v1/ws/rooms/${roomId}`);
      toast({ title: "Room deleted" });
      onDeleted?.();
      onOpenChange(false);
    } catch {
      toast({
        title: "Error",
        description: "Failed to delete room",
        variant: "destructive",
      });
    } finally {
      setDeleting(false);
    }
  }, [confirmDelete, roomId, toast, onDeleted, onOpenChange]);

  return (
    <Dialog onOpenChange={onOpenChange} open={open}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-base">
            <Hash className="size-5 text-primary/60" />
            Room Settings
          </DialogTitle>
          <DialogDescription>Customize #{roomName}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label className="text-[13px]" htmlFor="rs-name">
              Name
            </Label>
            <Input
              autoFocus
              id="rs-name"
              maxLength={100}
              onChange={(e) => setName(e.target.value)}
              value={name}
            />
          </div>

          <div className="space-y-2">
            <Label className="text-[13px]" htmlFor="rs-topic">
              Topic
            </Label>
            <Textarea
              className="resize-none text-sm"
              id="rs-topic"
              maxLength={500}
              onChange={(e) => setTopicText(e.target.value)}
              placeholder="What's this room about?"
              rows={2}
              value={topicText}
            />
          </div>

          <div className="space-y-2">
            <Label className="text-[13px]" htmlFor="rs-category">
              Category
            </Label>
            <NativeSelect
              id="rs-category"
              onChange={(e) => setCategory(e.target.value)}
              value={category}
            >
              <option value="">No category</option>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>
                  {cat.name}
                </option>
              ))}
            </NativeSelect>
          </div>

          <div className="flex items-center justify-between rounded-lg border border-border/30 px-3 py-2.5">
            <div className="space-y-0.5">
              <Label className="text-[13px] font-medium" htmlFor="rs-public">
                Public channel
              </Label>
              <p className="text-[11px] text-muted-foreground/40">
                Anyone in the workspace can join
              </p>
            </div>
            <Switch
              checked={isPublic}
              id="rs-public"
              onCheckedChange={setIsPublic}
            />
          </div>

          <div className="flex items-center justify-between rounded-lg border border-border/30 px-3 py-2.5">
            <div className="space-y-0.5">
              <Label className="text-[13px] font-medium" htmlFor="rs-ai">
                AI Assistant
              </Label>
              <p className="text-[11px] text-muted-foreground/40">
                Enable AI responses in this channel
              </p>
            </div>
            <Switch
              checked={aiEnabledState}
              id="rs-ai"
              onCheckedChange={setAiEnabledState}
            />
          </div>

          <div className="rounded-lg border border-destructive/10 bg-destructive/[0.02] p-3">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-destructive/80">
                  Delete channel
                </p>
                <p className="text-[11px] text-muted-foreground/40">
                  This action cannot be undone.
                </p>
              </div>
              {!confirmDelete ? (
                <Button
                  className="cursor-pointer"
                  onClick={handleDelete}
                  size="sm"
                  variant="destructive"
                >
                  <Trash2 className="mr-1.5 size-3.5" />
                  Delete
                </Button>
              ) : (
                <Button
                  className="cursor-pointer"
                  disabled={deleting}
                  onClick={handleDelete}
                  size="sm"
                  variant="destructive"
                >
                  {deleting && (
                    <Loader2 className="mr-1.5 size-3.5 animate-spin" />
                  )}
                  Confirm Delete
                </Button>
              )}
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button
            className="cursor-pointer"
            onClick={() => onOpenChange(false)}
            variant="outline"
          >
            Cancel
          </Button>
          <Button
            className="cursor-pointer"
            disabled={saving || !name.trim()}
            onClick={handleSave}
          >
            {saving && <Loader2 className="mr-2 size-4 animate-spin" />}
            Save Changes
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
