'use client';

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

export interface ErrorMessageProps {
  error: any;
  showErrorCode?: boolean;
  variant?: 'standard' | 'filled' | 'outlined';
  severity?: 'error' | 'warning';
  onClose?: () => void;
  sx?: any;
}

/**
 * ErrorMessage Component
 * Displays error messages inline (within forms, pages, etc.)
 * Preserves backend multilingual error messages
 */
export function ErrorMessage({
  error,
  showErrorCode = false,
  variant = 'standard',
  severity = 'error',
  onClose,
  sx,
}: ErrorMessageProps) {
  if (!error) {
    return null;
  }

  const extracted = extractError(error);

  return (
    <Box sx={{ mb: 2, ...sx }}>
      <Alert severity={severity} variant={variant} onClose={onClose}>
        {showErrorCode && extracted.code && (
          <AlertTitle sx={{ fontWeight: 600 }}>{extracted.code}</AlertTitle>
        )}
        {extracted.message}
      </Alert>
    </Box>
  );
}

/**
 * FieldError Component
 * Displays field-specific error messages (for form fields)
 */
export interface FieldErrorProps {
  error: any;
  fieldName: string;
  sx?: any;
}

export function FieldError({ error, fieldName, sx }: FieldErrorProps) {
  if (!error) {
    return null;
  }

  const extracted = extractError(error);

  // Only show if this error is for the specific field
  if (extracted.field !== fieldName) {
    return null;
  }

  return (
    <Box sx={{ mt: 0.5, ...sx }}>
      <Alert severity="error" variant="outlined" sx={{ py: 0.5, px: 1 }}>
        {extracted.message}
      </Alert>
    </Box>
  );
}

/**
 * ErrorList Component
 * Displays multiple errors in a list
 */
export interface ErrorListProps {
  errors: any[];
  showErrorCodes?: boolean;
  variant?: 'standard' | 'filled' | 'outlined';
  onClose?: () => void;
  sx?: any;
}

export function ErrorList({
  errors,
  showErrorCodes = false,
  variant = 'standard',
  onClose,
  sx,
}: ErrorListProps) {
  if (!errors || errors.length === 0) {
    return null;
  }

  const extractedErrors = errors.map((err) => extractError(err));

  return (
    <Box sx={{ mb: 2, ...sx }}>
      <Alert severity="error" variant={variant} onClose={onClose}>
        <AlertTitle sx={{ fontWeight: 600 }}>Multiple errors occurred:</AlertTitle>
        <ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
          {extractedErrors.map((err, index) => (
            <li key={index} style={{ marginBottom: '4px' }}>
              {showErrorCodes && err.code && <strong>{err.code}: </strong>}
              {err.message}
            </li>
          ))}
        </ul>
      </Alert>
    </Box>
  );
}

/**
 * Hook to manage error message state
 */
export function useErrorMessage() {
  const [error, setError] = React.useState<any>(null);

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

  const clearError = () => {
    setError(null);
  };

  const hasError = error !== null;

  return {
    error,
    showError,
    clearError,
    hasError,
  };
}
