'use client';

import React from 'react';
import { Snackbar, Alert, AlertTitle } from '@mui/material';
import { extractError } from '@/lib/utils/errorHandler';

export interface ErrorToastProps {
  error: any;
  open: boolean;
  onClose: () => void;
  autoHideDuration?: number;
  showErrorCode?: boolean;
}

/**
 * ErrorToast Component
 * Displays error messages as a toast notification
 * Preserves backend multilingual error messages
 */
export function ErrorToast({
  error,
  open,
  onClose,
  autoHideDuration = 6000,
  showErrorCode = false,
}: ErrorToastProps) {
  if (!error) {
    return null;
  }

  const extracted = extractError(error);

  return (
    <Snackbar
      open={open}
      autoHideDuration={autoHideDuration}
      onClose={onClose}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
    >
      <Alert onClose={onClose} severity="error" variant="filled" sx={{ width: '100%' }}>
        {showErrorCode && extracted.code && (
          <AlertTitle>{extracted.code}</AlertTitle>
        )}
        {extracted.message}
      </Alert>
    </Snackbar>
  );
}

/**
 * Hook to manage error toast state
 */
export function useErrorToast() {
  const [error, setError] = React.useState<any>(null);
  const [open, setOpen] = React.useState(false);

  const showError = (err: any) => {
    setError(err);
    setOpen(true);
  };

  const hideError = () => {
    setOpen(false);
  };

  const handleClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
    if (reason === 'clickaway') {
      return;
    }
    hideError();
  };

  return {
    error,
    open,
    showError,
    hideError,
    handleClose,
  };
}
