/* eslint-disable @typescript-eslint/no-explicit-any */
import { chatAPI } from '@/lib/api';
import { useChatStore } from '@/stores/chatStore';
import type { ChatRoom, UpdateChatRoomRequest } from '@/types';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Loader2, Trash2, UserMinus, UserPlus } from 'lucide-react';
import { useState, type FC, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { Button } from './ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from './ui/dialog';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Textarea } from './ui/textarea';

type ChatRoomSettingsDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  room: ChatRoom | null;
};

export const ChatRoomSettingsDialog: FC<ChatRoomSettingsDialogProps> = ({
  open,
  onOpenChange,
  room,
}) => {
  const queryClient = useQueryClient();
  const navigate = useNavigate();
  const { updateChatRoom, removeChatRoom } = useChatStore();
  const [newMemberUsername, setNewMemberUsername] = useState('');
  const [formData, setFormData] = useState<UpdateChatRoomRequest>({
    name: room?.name || '',
    description: room?.description || '',
  });

  useState(() => {
    if (room) {
      setFormData({
        name: room.name,
        description: room.description || '',
      });
    }
  });

  const updateRoomMutation = useMutation({
    mutationKey: ['updateChatRoom'],
    mutationFn: (data: UpdateChatRoomRequest) =>
      chatAPI.updateChatRoom(room?.id || '', data),
    onSuccess: (response) => {
      if (response.data.success) {
        updateChatRoom(response.data.data);
        toast.success('Chat room updated successfully');
      }
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.error || 'Failed to update chat room');
    },
  });

  const addMemberMutation = useMutation({
    mutationKey: ['addMember'],
    mutationFn: (username: string) =>
      chatAPI.addChatRoomMember(room?.id || '', { username }),
    onSuccess: (response) => {
      if (response.data.success) {
        updateChatRoom(response.data.data);
        setNewMemberUsername('');
        toast.success('Member added successfully');
      }
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.error || 'Failed to add member');
    },
  });

  const removeMemberMutation = useMutation({
    mutationKey: ['removeMember'],
    mutationFn: (userId: string) =>
      chatAPI.removeChatRoomMember(room?.id || '', { userId }),
    onSuccess: (response) => {
      if (response.data.success) {
        updateChatRoom(response.data.data);
        toast.success('Member removed successfully');
      }
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.error || 'Failed to remove member');
    },
  });

  const deleteRoomMutation = useMutation({
    mutationKey: ['deleteChatRoom'],
    mutationFn: () => chatAPI.deleteChatRoom(room?.id || ''),
    onSuccess: (response) => {
      if (response.data.success) {
        removeChatRoom(room?.id || '');
        onOpenChange(false);
        navigate('/');
        toast.success('Chat room deleted successfully');
        queryClient.invalidateQueries({ queryKey: ['chatRooms'] });
      }
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.error || 'Failed to delete chat room');
    },
  });

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    if (room) {
      updateRoomMutation.mutate(formData);
    }
  };

  const handleAddMember = (e: FormEvent) => {
    e.preventDefault();
    if (room && newMemberUsername) {
      addMemberMutation.mutate(newMemberUsername);
    }
  };

  const handleRemoveMember = (userId: string) => {
    if (room) {
      removeMemberMutation.mutate(userId);
    }
  };

  const handleDeleteRoom = () => {
    if (
      window.confirm(
        'Are you sure you want to delete this chat room? This action cannot be undone.'
      )
    ) {
      deleteRoomMutation.mutate();
    }
  };

  if (!room) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Room Settings</DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">Room Name</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) =>
                setFormData({ ...formData, name: e.target.value })
              }
              required
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) =>
                setFormData({ ...formData, description: e.target.value })
              }
              placeholder="Room description (optional)"
            />
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={updateRoomMutation.isPending}>
              {updateRoomMutation.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                'Save Changes'
              )}
            </Button>
          </div>
        </form>

        <div className="space-y-4 pt-4 border-t">
          <div>
            <h3 className="text-sm font-medium mb-2">
              Members ({room.members.length})
            </h3>
            <div className="space-y-2 max-h-40 overflow-y-auto">
              {room.members.map((member) => (
                <div
                  key={member.id}
                  className="flex items-center justify-between"
                >
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-blue-500 text-white flex items-center justify-center text-xs">
                      {member.user.avatar ? (
                        <img
                          src={member.user.avatar}
                          alt={member.user.username}
                          className="w-full h-full rounded-full"
                        />
                      ) : (
                        member.user.username.charAt(0).toUpperCase()
                      )}
                    </div>
                    <span className="text-sm">{member.user.username}</span>
                    {member.role === 'admin' && (
                      <span className="text-xs text-gray-500">(admin)</span>
                    )}
                  </div>
                  {member.role !== 'admin' && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveMember(member.userId)}
                      disabled={removeMemberMutation.isPending}
                    >
                      <UserMinus className="h-4 w-4 text-red-500" />
                    </Button>
                  )}
                </div>
              ))}
            </div>
          </div>

          <form onSubmit={handleAddMember} className="flex gap-2">
            <Input
              placeholder="Add member by username"
              value={newMemberUsername}
              onChange={(e) => setNewMemberUsername(e.target.value)}
              className="flex-1"
            />
            <Button
              type="submit"
              size="sm"
              disabled={!newMemberUsername || addMemberMutation.isPending}
            >
              <UserPlus className="h-4 w-4" />
            </Button>
          </form>

          <div className="pt-4 border-t">
            <Button
              variant="destructive"
              className="w-full"
              onClick={handleDeleteRoom}
              disabled={deleteRoomMutation.isPending}
            >
              {deleteRoomMutation.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Deleting...
                </>
              ) : (
                <>
                  <Trash2 className="mr-2 h-4 w-4" />
                  Delete Room
                </>
              )}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
};
