import { Trash2 } from 'lucide-react';
import {
  useIsConfirmDeleteModalOpen,
  useSetIsConfirmDeleteModalOpen,
  useConfirmDeleteConversationName,
  useConfirmDeleteConversationId
} from '../../contexts/UIContext';
import { useDeleteConversation, useCurrentConversationId } from '../../contexts/ChatContext';
import { useAppRoute } from '../../hooks/useAppRoute';
import useRenderTracker from '../../hooks/useRenderTracker';
import { Button } from '../ui';

const ConfirmDeleteModal = () => {

  const isConfirmDeleteModalOpen = useIsConfirmDeleteModalOpen();
  const setIsConfirmDeleteModalOpen = useSetIsConfirmDeleteModalOpen();
  const confirmDeleteConversationName = useConfirmDeleteConversationName();
  const confirmDeleteConversationId = useConfirmDeleteConversationId();
  const currentConversationId = useCurrentConversationId();
  const deleteConversation = useDeleteConversation();
  const { openHomeRoute } = useAppRoute();

  useRenderTracker('ConfirmDeleteModal', {
    isConfirmDeleteModalOpen,
    confirmDeleteConversationName,
    confirmDeleteConversationId,
    deleteConversation,
    setIsConfirmDeleteModalOpen,
  });

  if (!isConfirmDeleteModalOpen) return null;

  const close = () => setIsConfirmDeleteModalOpen(false);

  const handleDelete = () => {
    if (confirmDeleteConversationId) {
      // If the conversation being deleted is the one open, return to the new-chat page.
      if (confirmDeleteConversationId === currentConversationId) {
        openHomeRoute();
      }
      deleteConversation(confirmDeleteConversationId);
      setIsConfirmDeleteModalOpen(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <button
        type="button"
        aria-label="Close"
        className="absolute inset-0 bg-black/45 backdrop-blur-sm"
        onClick={close}
      />
      <div
        role="dialog"
        aria-modal="true"
        className="relative z-10 w-full max-w-sm overflow-hidden rounded-2xl border border-app-border bg-app-surface shadow-2xl"
      >
        <div className="p-6">
          <div className="flex h-11 w-11 items-center justify-center rounded-full bg-danger/10 text-danger">
            <Trash2 size={20} />
          </div>
          <h2 className="mt-4 text-lg font-semibold text-app-text">Delete conversation?</h2>
          <p className="mt-1.5 text-sm leading-6 text-app-muted">
            This will permanently delete{' '}
            <span className="font-medium text-app-text">“{confirmDeleteConversationName || 'New Chat'}”</span>.
            This can’t be undone.
          </p>
        </div>
        <div className="flex justify-end gap-2 border-t border-app-border bg-app-surface-muted px-6 py-4">
          <Button onClick={close}>Cancel</Button>
          <Button variant="danger" onClick={handleDelete}>Delete</Button>
        </div>
      </div>
    </div>
  );
};

export default ConfirmDeleteModal;
