/**
 * @ai-summary File input fallback for desktop and unsupported browsers
 * @ai-context Provides drag-drop and click-to-browse file selection
 */

import React, { useRef, useState, useCallback } from 'react';
import { Box, Typography, Button, Alert } from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CloseIcon from '@mui/icons-material/Close';
import type { FileInputFallbackProps } from './types';

export const FileInputFallback: React.FC<FileInputFallbackProps> = ({
  onFileSelect,
  onCancel,
  acceptedFormats,
  maxFileSize,
}) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const validateFile = useCallback(
    (file: File): string | null => {
      // Check file type
      const isValidType =
        acceptedFormats.length === 0 ||
        acceptedFormats.some((format) => {
          // Handle HEIC/HEIF which may have different MIME types
          if (format === 'image/heic' || format === 'image/heif') {
            return (
              file.type === 'image/heic' ||
              file.type === 'image/heif' ||
              file.name.toLowerCase().endsWith('.heic') ||
              file.name.toLowerCase().endsWith('.heif')
            );
          }
          return file.type === format;
        });

      if (!isValidType) {
        return `Invalid file type. Accepted formats: ${acceptedFormats.join(', ')}`;
      }

      // Check file size
      if (file.size > maxFileSize) {
        const maxSizeMB = (maxFileSize / (1024 * 1024)).toFixed(1);
        return `File too large. Maximum size: ${maxSizeMB}MB`;
      }

      return null;
    },
    [acceptedFormats, maxFileSize]
  );

  const handleFile = useCallback(
    (file: File) => {
      setError(null);
      const validationError = validateFile(file);

      if (validationError) {
        setError(validationError);
        return;
      }

      onFileSelect(file);
    },
    [validateFile, onFileSelect]
  );

  const handleInputChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      if (file) {
        handleFile(file);
      }
      // Reset input so same file can be selected again
      if (inputRef.current) {
        inputRef.current.value = '';
      }
    },
    [handleFile]
  );

  const handleDragOver = useCallback((event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(
    (event: React.DragEvent) => {
      event.preventDefault();
      event.stopPropagation();
      setIsDragging(false);

      const file = event.dataTransfer.files[0];
      if (file) {
        handleFile(file);
      }
    },
    [handleFile]
  );

  const handleClick = useCallback(() => {
    inputRef.current?.click();
  }, []);

  // Generate accept string for input
  const acceptString = acceptedFormats.join(',');

  return (
    <Box
      sx={{
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        backgroundColor: 'background.paper',
      }}
    >
      {/* Header */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          p: 2,
          borderBottom: 1,
          borderColor: 'divider',
        }}
      >
        <Typography variant="h6">Upload Image</Typography>
        <Button
          onClick={onCancel}
          startIcon={<CloseIcon />}
          color="inherit"
          aria-label="Cancel"
        >
          Cancel
        </Button>
      </Box>

      {/* Drop zone */}
      <Box
        sx={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          p: 3,
        }}
      >
        <Box
          onClick={handleClick}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          onDrop={handleDrop}
          sx={{
            width: '100%',
            maxWidth: 400,
            py: 6,
            px: 4,
            border: 2,
            borderStyle: 'dashed',
            borderColor: isDragging ? 'primary.main' : 'divider',
            borderRadius: 2,
            backgroundColor: isDragging ? 'action.hover' : 'transparent',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2,
            cursor: 'pointer',
            transition: 'all 0.2s ease',
            '&:hover': {
              borderColor: 'primary.main',
              backgroundColor: 'action.hover',
            },
          }}
        >
          <CloudUploadIcon
            sx={{
              fontSize: 64,
              color: isDragging ? 'primary.main' : 'text.secondary',
            }}
          />

          <Typography
            variant="body1"
            color={isDragging ? 'primary.main' : 'text.primary'}
            textAlign="center"
          >
            {isDragging
              ? 'Drop image here'
              : 'Drag and drop an image, or click to browse'}
          </Typography>

          <Typography variant="caption" color="text.secondary" textAlign="center">
            Supported formats: JPEG, PNG, HEIC
          </Typography>

          <Typography variant="caption" color="text.secondary">
            Maximum size: {(maxFileSize / (1024 * 1024)).toFixed(0)}MB
          </Typography>
        </Box>

        {error && (
          <Alert severity="error" sx={{ mt: 2, maxWidth: 400, width: '100%' }}>
            {error}
          </Alert>
        )}

        {/* Hidden file input */}
        <input
          ref={inputRef}
          type="file"
          accept={acceptString}
          onChange={handleInputChange}
          style={{ display: 'none' }}
          aria-label="Select image file"
        />
      </Box>

      {/* Mobile-friendly button */}
      <Box
        sx={{
          p: 2,
          borderTop: 1,
          borderColor: 'divider',
          display: { xs: 'block', sm: 'none' },
        }}
      >
        <Button
          variant="contained"
          fullWidth
          onClick={handleClick}
          startIcon={<CloudUploadIcon />}
          size="large"
        >
          Choose Image
        </Button>
      </Box>
    </Box>
  );
};

export default FileInputFallback;
