import { CloudUpload as CloudUploadIcon } from '@mui/icons-material';
import { Alert, Box, Button, CircularProgress } from '@mui/material';
import { AxiosError } from 'axios';
import React, { useState } from 'react';
import { documentApi } from '../../api/client';
import { ApiError } from '../../types/api';
import { DocumentType } from '../../types/document';

interface DocumentUploadProps {
  onUploadSuccess: (documentId: string) => void;
  documentType: DocumentType;
  label: string;
}

export const DocumentUpload = ({ onUploadSuccess, documentType, label }: DocumentUploadProps) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setLoading(true);
    setError('');
    setSuccess(false);

    try {
      const response = await documentApi.upload(file, documentType);
      console.log('Document upload response:', response.data);
      const documentId = response.data.data.id;
      console.log('Extracted document ID:', documentId);
      onUploadSuccess(documentId);
      setSuccess(true);
    } catch (err) {
      if (err instanceof AxiosError && err.response?.data) {
        const apiError = err.response.data as ApiError;
        const messages = Array.isArray(apiError.message)
          ? apiError.message.map((m) => `${m.field}: ${m.message}`).join('\n')
          : apiError.message;
        setError(messages);
      } else {
        setError(err instanceof Error ? err.message : 'Failed to upload document');
      }
    } finally {
      setLoading(false);
    }
  };

  const now = new Date();
  return (
    <Box>
      <input
        accept="image/*,.pdf"
        style={{ display: 'none' }}
        id={`upload-${documentType}-${now.getTime()}`}
        type="file"
        onChange={handleFileChange}
        disabled={loading}
      />
      <label htmlFor={`upload-${documentType}-${now.getTime()}`}>
        <Button
          variant="outlined"
          component="span"
          startIcon={loading ? <CircularProgress size={20} /> : <CloudUploadIcon />}
          disabled={loading}
          fullWidth
        >
          {loading ? 'Uploading...' : label}
        </Button>
      </label>

      {error && (
        <Alert severity="error" sx={{ mt: 1, whiteSpace: 'pre-line' }}>
          {error}
        </Alert>
      )}

      {success && (
        <Alert severity="success" sx={{ mt: 1 }}>
          Document uploaded successfully
        </Alert>
      )}
    </Box>
  );
};
