import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  IconButton,
  Chip,
  CircularProgress,
  Alert,
  Button,
  Breadcrumbs,
  Link
} from '@mui/material';
import { useParams, useNavigate, Link as RouterLink } from 'react-router-dom';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import { useCouponRedemptions, useAdminCoupon } from '@hooks/couponAdminHooks';
import { format } from 'date-fns';

const CouponRedemptionsPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  
  // Fetch coupon details
  const { data: coupon, isLoading: couponLoading, error: couponError } = useAdminCoupon(id);
  
  // Fetch redemption history
  const { data: redemptions, isLoading: redemptionsLoading, error: redemptionsError } = useCouponRedemptions(id);
  
  // Handle page change
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };
  
  // Handle rows per page change
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
      return format(new Date(dateString), 'MMM d, yyyy h:mm a');
    } catch (error) {
      return dateString;
    }
  };
  
  // Loading state
  const isLoading = couponLoading || redemptionsLoading;
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  const error = couponError || redemptionsError;
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading data: {error.message}
      </Alert>
    );
  }
  
  // Paginate redemptions
  const paginatedRedemptions = redemptions ? redemptions.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  ) : [];
  
  return (
    <Box>
      <Box sx={{ mb: 3 }}>
        <Button
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate('/admin/coupons')}
          sx={{ mb: 2 }}
        >
          Back to Coupons
        </Button>
        
        <Breadcrumbs sx={{ mb: 2 }}>
          <Link component={RouterLink} to="/admin" color="inherit">
            Admin
          </Link>
          <Link component={RouterLink} to="/admin/coupons" color="inherit">
            Coupons
          </Link>
          <Typography color="text.primary">Redemptions</Typography>
        </Breadcrumbs>
        
        <Typography variant="h4" component="h1" gutterBottom>
          Redemption History: {coupon?.code}
        </Typography>
        
        <Paper sx={{ p: 3, mb: 3 }}>
          <Typography variant="h6" gutterBottom>
            Coupon Details
          </Typography>
          <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            <Box>
              <Typography variant="subtitle2" color="text.secondary">Code</Typography>
              <Typography variant="body1">{coupon?.code}</Typography>
            </Box>
            <Box>
              <Typography variant="subtitle2" color="text.secondary">Discount</Typography>
              <Typography variant="body1">
                {coupon?.discount_type === 'percentage' 
                  ? `${coupon.discount_value}%` 
                  : `$${parseFloat(coupon.discount_value).toFixed(2)}`}
              </Typography>
            </Box>
            <Box>
              <Typography variant="subtitle2" color="text.secondary">Usage</Typography>
              <Typography variant="body1">
                {coupon?.current_redemptions} / {coupon?.redemption_limit || 'Unlimited'}
              </Typography>
            </Box>
            <Box>
              <Typography variant="subtitle2" color="text.secondary">Status</Typography>
              <Chip 
                label={coupon?.is_active ? 'Active' : 'Inactive'} 
                color={coupon?.is_active ? 'success' : 'default'} 
                size="small"
              />
            </Box>
          </Box>
        </Paper>
      </Box>
      
      {/* Redemptions Table */}
      <Paper>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Customer</TableCell>
                <TableCell>Date</TableCell>
                <TableCell>Order #</TableCell>
                <TableCell align="right">Order Total</TableCell>
                <TableCell align="right">Discount Amount</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedRedemptions.length > 0 ? (
                paginatedRedemptions.map((redemption) => (
                  <TableRow key={redemption.id}>
                    <TableCell>
                      <Typography variant="body2">
                        {redemption.first_name} {redemption.last_name}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {redemption.email}
                      </Typography>
                    </TableCell>
                    <TableCell>{formatDate(redemption.redeemed_at)}</TableCell>
                    <TableCell>
                      <Link 
                        component={RouterLink} 
                        to={`/admin/orders/${redemption.order_id}`}
                      >
                        {redemption.order_id.substring(0, 8)}...
                      </Link>
                    </TableCell>
                    <TableCell align="right">
                      ${parseFloat(redemption.total_amount).toFixed(2)}
                    </TableCell>
                    <TableCell align="right">
                      ${parseFloat(redemption.discount_amount).toFixed(2)}
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={5} align="center">
                    <Typography variant="body1" py={2}>
                      No redemptions found for this coupon.
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        {redemptions && redemptions.length > 0 && (
          <TablePagination
            rowsPerPageOptions={[5, 10, 25, 50]}
            component="div"
            count={redemptions.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
        )}
      </Paper>
    </Box>
  );
};

export default CouponRedemptionsPage;