import React, { useState, useCallback } from 'react';
import { TextField, Button, Grid, Paper, Typography, CircularProgress } from '@mui/material';
import { useAppDispatch, useAppSelector } from '../../hooks/redux';
import { createInvoice } from '../../store/slices/invoiceSlice';
import { InvoiceFormData } from '../../types/invoice';

interface InvoiceFormProps {
  onSubmit?: (data: InvoiceFormData) => void;
}

const InvoiceForm: React.FC<InvoiceFormProps> = ({ onSubmit }) => {
  const dispatch = useAppDispatch();
  const { loading, error } = useAppSelector((state) => state.invoice);

  const [formData, setFormData] = useState<InvoiceFormData>({
    customerName: '',
    email: '',
    amount: '',
    dueDate: '',
    description: ''
  });

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value
    }));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await dispatch(createInvoice(formData)).unwrap();
      onSubmit?.(formData);
      setFormData({
        customerName: '',
        email: '',
        amount: '',
        dueDate: '',
        description: ''
      });
    } catch (err) {
      console.error('Failed to create invoice:', err);
    }
  };

  return (
    <Paper elevation={3} sx={{ p: 3, maxWidth: 600, mx: 'auto' }}>
      <Typography variant="h5" component="h2" gutterBottom>
        Create New Invoice
      </Typography>
      <form onSubmit={handleSubmit} aria-label="invoice-form">
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <TextField
              required
              fullWidth
              label="Customer Name"
              name="customerName"
              value={formData.customerName}
              onChange={handleChange}
              error={!!error}
              aria-label="customer-name"
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              required
              fullWidth
              type="email"
              label="Email"
              name="email"
              value={formData.email}
              onChange={handleChange}
              error={!!error}
              aria-label="email"
            />
          </Grid>
          <Grid item xs={12} sm={6}>
            <TextField
              required
              fullWidth
              type="number"
              label="Amount"
              name="amount"
              value={formData.amount}
              onChange={handleChange}
              error={!!error}
              aria-label="amount"
            />
          </Grid>
          <Grid item xs={12} sm={6}>
            <TextField
              required
              fullWidth
              type="date"
              label="Due Date"
              name="dueDate"
              value={formData.dueDate}
              onChange={handleChange}
              error={!!error}
              InputLabelProps={{ shrink: true }}
              aria-label="due-date"
            />
          </Grid>
          <Grid item xs={12}>
            <TextField
              fullWidth
              multiline
              rows={4}
              label="Description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              error={!!error}
              aria-label="description"
            />
          </Grid>
          <Grid item xs={12}>
            <Button
              type="submit"
              variant="contained"
              color="primary"
              fullWidth
              disabled={loading}
              aria-label="submit-invoice"
            >
              {loading ? <CircularProgress size={24} /> : 'Create Invoice'}
            </Button>
          </Grid>
        </Grid>
      </form>
    </Paper>
  );
};

export default React.memo(InvoiceForm);