import React, { Component } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Paper,
  Alert,
  CircularProgress,
  FormControl,
  FormLabel,
  RadioGroup,
  FormControlLabel,
  Radio
} from '@mui/material';
import { withI18n } from '../i18n/withTranslation.js';

class ArticleAvailabilityForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      email: '',
      telegramId: '',
      notificationMethod: 'email',
      message: '',
      loading: false,
      success: false,
      error: null
    };
  }

  handleInputChange = (field) => (event) => {
    this.setState({ [field]: event.target.value });
  };

  handleNotificationMethodChange = (event) => {
    this.setState({ 
      notificationMethod: event.target.value,
      // Clear the other field when switching methods
      email: event.target.value === 'email' ? this.state.email : '',
      telegramId: event.target.value === 'telegram' ? this.state.telegramId : ''
    });
  };

  handleSubmit = (event) => {
    event.preventDefault();
    
    // Prepare data for API emission
    const availabilityData = {
      type: 'availability_inquiry',
      productId: this.props.productId,
      productName: this.props.productName,
      name: this.state.name,
      notificationMethod: this.state.notificationMethod,
      email: this.state.notificationMethod === 'email' ? this.state.email : '',
      telegramId: this.state.notificationMethod === 'telegram' ? this.state.telegramId : '',
      message: this.state.message,
      timestamp: new Date().toISOString()
    };

    // Emit data via socket
    console.log('Availability Inquiry Data to emit:', availabilityData);
    
      window.socketManager.emit('availability_inquiry_submit', availabilityData);
      
      // Set up response handler
      window.socketManager.once('availability_inquiry_response', (response) => {
        if (response.success) {
          this.setState({ 
            loading: false,
            success: true,
            name: '',
            email: '',
            telegramId: '',
            notificationMethod: 'email',
            message: ''
          });
        } else {
          this.setState({ 
            loading: false,
            error: response.error || this.props.t("productDialogs.errorGeneric")
          });
        }
        
        // Clear messages after 3 seconds
        setTimeout(() => {
          this.setState({ success: false, error: null });
        }, 3000);
      });
    
    this.setState({ loading: true });
    
    // Fallback timeout in case backend doesn't respond
    setTimeout(() => {
      if (this.state.loading) {
        this.setState({ 
          loading: false,
          success: true,
          name: '',
          email: '',
          telegramId: '',
          notificationMethod: 'email',
          message: ''
        });
        
        // Clear success message after 3 seconds
        setTimeout(() => {
          this.setState({ success: false });
        }, 3000);
      }
    }, 5000);
  };

  render() {
    const { name, email, telegramId, notificationMethod, message, loading, success, error } = this.state;
    const { t } = this.props;

    return (
      <Paper id="availability-form" sx={{ p: 3, mt: 4, borderRadius: 2, boxShadow: "0 2px 8px rgba(0,0,0,0.08)" }}>
        <Typography variant="h5" gutterBottom sx={{ fontWeight: 600, color: '#333' }}>
          {t("productDialogs.availabilityTitle")}
        </Typography>
        
        <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
          {t("productDialogs.availabilitySubtitle")}
        </Typography>

        {success && (
          <Alert severity="success" sx={{ mb: 3 }}>
            {notificationMethod === 'email' ? t("productDialogs.availabilitySuccessEmail") : t("productDialogs.availabilitySuccessTelegram")}
          </Alert>
        )}

        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        <Box component="form" onSubmit={this.handleSubmit} sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <TextField
            label={t("productDialogs.nameLabel")}
            value={name}
            onChange={this.handleInputChange('name')}
            required
            fullWidth
            disabled={loading}
            placeholder={t("productDialogs.namePlaceholder")}
          />

          <FormControl component="fieldset" disabled={loading}>
            <FormLabel component="legend" sx={{ mb: 1 }}>
              {t("productDialogs.notificationMethodLabel")}
            </FormLabel>
            <RadioGroup
              value={notificationMethod}
              onChange={this.handleNotificationMethodChange}
              row
            >
              <FormControlLabel 
                value="email" 
                control={<Radio />} 
                label={t("productDialogs.emailLabel")}
              />
              <FormControlLabel 
                value="telegram" 
                control={<Radio />} 
                label={t("productDialogs.telegramBotLabel")}
              />
            </RadioGroup>
          </FormControl>
          
          {notificationMethod === 'email' && (
            <TextField
              label={t("productDialogs.emailLabel")}
              type="email"
              value={email}
              onChange={this.handleInputChange('email')}
              required
              fullWidth
              disabled={loading}
              placeholder={t("productDialogs.emailPlaceholder")}
            />
          )}

          {notificationMethod === 'telegram' && (
            <TextField
              label={t("productDialogs.telegramIdLabel")}
              value={telegramId}
              onChange={this.handleInputChange('telegramId')}
              required
              fullWidth
              disabled={loading}
              placeholder={t("productDialogs.telegramPlaceholder")}
              helperText={t("productDialogs.telegramHelper")}
            />
          )}
          
          <TextField
            label={t("productDialogs.messageLabel")}
            value={message}
            onChange={this.handleInputChange('message')}
            fullWidth
            multiline
            rows={3}
            disabled={loading}
            placeholder={t("productDialogs.messagePlaceholder")}
          />
          
          <Button
            type="submit"
            variant="contained"
            disabled={loading || !name || (notificationMethod === 'email' && !email) || (notificationMethod === 'telegram' && !telegramId)}
            sx={{ 
              mt: 2,
              py: 1.5,
              fontSize: '1rem',
              fontWeight: 600,
              backgroundColor: 'warning.main',
              '&:hover': {
                backgroundColor: 'warning.dark'
              }
            }}
          >
            {loading ? (
              <>
                <CircularProgress size={20} sx={{ mr: 1 }} />
                {t("productDialogs.sending")}
              </>
            ) : (
              t("productDialogs.submitAvailability")
            )}
          </Button>
        </Box>
      </Paper>
    );
  }
}

export default withI18n()(ArticleAvailabilityForm); 