import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  TextField,
  CircularProgress,
  Grid,
  Typography,
  Divider,
  Box
} from '@mui/material';
import { useUpdateOrderStatus } from '@hooks/adminHooks';

// List of supported shipping carriers
const SHIPPING_CARRIERS = [
  { value: 'Canada Post', label: 'Canada Post' },
  { value: 'Purolator', label: 'Purolator' },
  { value: 'USPS', label: 'USPS' },
  { value: 'UPS', label: 'UPS' },
  { value: 'FedEx', label: 'FedEx' },
  { value: 'DHL', label: 'DHL' },
  { value: 'other', label: 'Other (specify)' }
];

const OrderStatusDialog = ({ open, onClose, order }) => {
  const [status, setStatus] = useState(order ? order.status : 'pending');
  const [shippingData, setShippingData] = useState({
    shipper: '',
    otherShipper: '',
    trackingNumber: '',
    shipmentId: '',
    estimatedDelivery: '',
    customerMessage: ''
  });
  
  const updateOrderStatus = useUpdateOrderStatus();
  
  const handleStatusChange = (e) => {
    setStatus(e.target.value);
  };
  
  const handleShippingDataChange = (e) => {
    const { name, value } = e.target;
    setShippingData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  const handleSave = () => {
    // For shipped status, require tracking number
    if (status === 'shipped' && !shippingData.trackingNumber) {
      alert('Please enter a tracking number');
      return;
    }
    
    // Determine the actual shipper value to send
    let shipperValue = shippingData.shipper;
    if (shipperValue === 'other' && shippingData.otherShipper) {
      shipperValue = shippingData.otherShipper;
    }
    
    updateOrderStatus.mutate({
      orderId: order.id,
      status,
      ...(status === 'shipped' && {
        shippingData: {
          ...shippingData,
          shipper: shipperValue,
          // Add current date as shipped date if not provided
          shippedDate: new Date().toISOString().split('T')[0]
        },
        sendNotification: true
      })
    }, {
      onSuccess: () => {
        onClose();
      }
    });
  };
  
  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>Update Order Status</DialogTitle>
      <DialogContent dividers>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel id="status-select-label">Status</InputLabel>
              <Select
                labelId="status-select-label"
                value={status}
                label="Status"
                onChange={handleStatusChange}
              >
                <MenuItem value="pending">Pending</MenuItem>
                <MenuItem value="processing">Processing</MenuItem>
                <MenuItem value="shipped">Shipped</MenuItem>
                <MenuItem value="delivered">Delivered</MenuItem>
                <MenuItem value="cancelled">Cancelled</MenuItem>
                <MenuItem value="refunded">Refunded</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          
          {status === 'shipped' && (
            <>
              <Grid item xs={12}>
                <Divider sx={{ my: 1 }} />
                <Typography variant="subtitle1" gutterBottom>
                  Shipping Information
                </Typography>
                <Typography variant="body2" color="text.secondary" paragraph>
                  This information will be sent to the customer via email.
                </Typography>
              </Grid>
              
              <Grid item xs={12} md={6}>
                <FormControl fullWidth>
                  <InputLabel id="shipper-select-label">Shipping Carrier</InputLabel>
                  <Select
                    labelId="shipper-select-label"
                    name="shipper"
                    value={shippingData.shipper}
                    label="Shipping Carrier"
                    onChange={handleShippingDataChange}
                  >
                    {SHIPPING_CARRIERS.map((carrier) => (
                      <MenuItem key={carrier.value} value={carrier.value}>
                        {carrier.label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
              
              {shippingData.shipper === 'other' && (
                <Grid item xs={12} md={6}>
                  <TextField
                    fullWidth
                    label="Specify Carrier"
                    name="otherShipper"
                    value={shippingData.otherShipper}
                    onChange={handleShippingDataChange}
                    placeholder="Enter carrier name"
                  />
                </Grid>
              )}
              
              <Grid item xs={12} md={shippingData.shipper === 'other' ? 12 : 6}>
                <TextField
                  fullWidth
                  required
                  label="Tracking Number"
                  name="trackingNumber"
                  value={shippingData.trackingNumber}
                  onChange={handleShippingDataChange}
                  placeholder="Enter tracking number"
                  error={status === 'shipped' && !shippingData.trackingNumber}
                  helperText={status === 'shipped' && !shippingData.trackingNumber ? 'Tracking number is required' : ''}
                />
              </Grid>
              
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Shipment ID"
                  name="shipmentId"
                  value={shippingData.shipmentId}
                  onChange={handleShippingDataChange}
                  placeholder="Optional internal reference"
                />
              </Grid>
              
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Estimated Delivery"
                  name="estimatedDelivery"
                  value={shippingData.estimatedDelivery}
                  onChange={handleShippingDataChange}
                  placeholder="e.g., 3-5 business days"
                />
              </Grid>
              
              <Grid item xs={12}>
                <Divider sx={{ my: 1 }} />
                <TextField
                  fullWidth
                  multiline
                  rows={4}
                  label="Message to Customer"
                  name="customerMessage"
                  value={shippingData.customerMessage}
                  onChange={handleShippingDataChange}
                  placeholder="Add a personal message to the shipping notification email (optional)"
                />
              </Grid>
            </>
          )}
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button
          onClick={handleSave}
          variant="contained"
          color="primary"
          disabled={updateOrderStatus.isLoading}
        >
          {updateOrderStatus.isLoading ? <CircularProgress size={24} /> : 'Save'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default OrderStatusDialog;