import React, { useState } from 'react';
import {
  Box,
  Typography,
  Button,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  IconButton,
  TextField,
  InputAdornment,
  Chip,
  CircularProgress,
  Alert,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Tooltip
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Search as SearchIcon,
  Clear as ClearIcon,
  History as HistoryIcon
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useAdminCoupons, useDeleteCoupon } from '@hooks/couponAdminHooks';
import { format, isPast, isFuture } from 'date-fns';

const AdminCouponsPage = () => {
  const navigate = useNavigate();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [search, setSearch] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [couponToDelete, setCouponToDelete] = useState(null);
  
  // Fetch coupons
  const { data: coupons, isLoading, error } = useAdminCoupons();
  
  // Delete mutation
  const deleteCoupon = useDeleteCoupon();
  
  // Filter coupons by search
  const filteredCoupons = coupons ? coupons.filter(coupon => {
    const searchTerm = search.toLowerCase();
    return (
      coupon.code.toLowerCase().includes(searchTerm) || 
      (coupon.description && coupon.description.toLowerCase().includes(searchTerm))
    );
  }) : [];
  
  // Paginate coupons
  const paginatedCoupons = filteredCoupons.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );
  
  // Handle search change
  const handleSearchChange = (event) => {
    setSearch(event.target.value);
    setPage(0);
  };
  
  // Clear search
  const handleClearSearch = () => {
    setSearch('');
    setPage(0);
  };
  
  // 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);
  };
  
  // Handle edit action
  const handleEditCoupon = (id) => {
    navigate(`/admin/coupons/${id}`);
  };
  
  // Handle delete click
  const handleDeleteClick = (coupon) => {
    setCouponToDelete(coupon);
    setDeleteDialogOpen(true);
  };
  
  // Confirm delete
  const handleConfirmDelete = () => {
    if (couponToDelete) {
      deleteCoupon.mutate(couponToDelete.id, {
        onSuccess: () => {
          setDeleteDialogOpen(false);
          setCouponToDelete(null);
        }
      });
    }
  };
  
  // Cancel delete
  const handleCancelDelete = () => {
    setDeleteDialogOpen(false);
    setCouponToDelete(null);
  };
  
  // Navigate to view redemptions
  const handleViewRedemptions = (id) => {
    navigate(`/admin/coupons/${id}/redemptions`);
  };
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return 'No Date Set';
    try {
      return format(new Date(dateString), 'MMM d, yyyy');
    } catch (error) {
      return dateString;
    }
  };
  
  // Get coupon status
  const getCouponStatus = (coupon) => {
    if (!coupon.is_active) {
      return { label: 'Inactive', color: 'default' };
    }
    
    if (coupon.start_date && isFuture(new Date(coupon.start_date))) {
      return { label: 'Scheduled', color: 'info' };
    }
    
    if (coupon.end_date && isPast(new Date(coupon.end_date))) {
      return { label: 'Expired', color: 'error' };
    }
    
    if (coupon.redemption_limit !== null && coupon.current_redemptions >= coupon.redemption_limit) {
      return { label: 'Fully Redeemed', color: 'warning' };
    }
    
    return { label: 'Active', color: 'success' };
  };
  
  // Loading state
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }
  
  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading coupons: {error.message}
      </Alert>
    );
  }
  
  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" component="h1">
          Coupons & Discounts
        </Typography>
        
        <Button
          variant="contained"
          color="primary"
          startIcon={<AddIcon />}
          onClick={() => navigate('/admin/coupons/new')}
        >
          Add Coupon
        </Button>
      </Box>
      
      {/* Search Box */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <TextField
          fullWidth
          placeholder="Search coupons by code or description..."
          value={search}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
            endAdornment: search && (
              <InputAdornment position="end">
                <IconButton size="small" onClick={handleClearSearch}>
                  <ClearIcon />
                </IconButton>
              </InputAdornment>
            )
          }}
        />
      </Paper>
      
      {/* Coupons Table */}
      <Paper>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Code</TableCell>
                <TableCell>Type</TableCell>
                <TableCell>Value</TableCell>
                <TableCell>Status</TableCell>
                <TableCell>Redemptions</TableCell>
                <TableCell>Valid Period</TableCell>
                <TableCell align="right">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedCoupons.length > 0 ? (
                paginatedCoupons.map((coupon) => {
                  const status = getCouponStatus(coupon);
                  
                  return (
                    <TableRow key={coupon.id}>
                      <TableCell>
                        <Typography variant="body2" sx={{ fontWeight: 'bold' }}>
                          {coupon.code}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {coupon.description || 'No description'}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        {coupon.discount_type === 'percentage' ? 'Percentage' : 'Fixed Amount'}
                      </TableCell>
                      <TableCell>
                        {coupon.discount_type === 'percentage' 
                          ? `${coupon.discount_value}%` 
                          : `$${parseFloat(coupon.discount_value).toFixed(2)}`}
                        {coupon.max_discount_amount && (
                          <Typography variant="caption" display="block" color="text.secondary">
                            Max: ${parseFloat(coupon.max_discount_amount).toFixed(2)}
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={status.label} 
                          color={status.color} 
                          size="small" 
                        />
                      </TableCell>
                      <TableCell>
                        {coupon.redemption_limit ? (
                          <Typography variant="body2">
                            {coupon.current_redemptions} / {coupon.redemption_limit}
                          </Typography>
                        ) : (
                          <Typography variant="body2">
                            {coupon.current_redemptions} / Unlimited
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell>
                        {coupon.start_date && (
                          <Typography variant="caption" display="block">
                            From: {formatDate(coupon.start_date)}
                          </Typography>
                        )}
                        {coupon.end_date ? (
                          <Typography variant="caption" display="block">
                            To: {formatDate(coupon.end_date)}
                          </Typography>
                        ) : (
                          <Typography variant="caption" display="block">
                            No End Date
                          </Typography>
                        )}
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="View Redemption History">
                          <IconButton
                            onClick={() => handleViewRedemptions(coupon.id)}
                            color="primary"
                          >
                            <HistoryIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Edit Coupon">
                          <IconButton
                            onClick={() => handleEditCoupon(coupon.id)}
                            color="primary"
                          >
                            <EditIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="Delete Coupon">
                          <IconButton
                            onClick={() => handleDeleteClick(coupon)}
                            color="error"
                          >
                            <DeleteIcon />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Typography variant="body1" py={2}>
                      {search ? 'No coupons match your search.' : 'No coupons found.'}
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 50]}
          component="div"
          count={filteredCoupons.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Paper>
      
      {/* Delete Confirmation Dialog */}
      <Dialog
        open={deleteDialogOpen}
        onClose={handleCancelDelete}
        aria-labelledby="delete-dialog-title"
        aria-describedby="delete-dialog-description"
      >
        <DialogTitle id="delete-dialog-title">
          Confirm Delete
        </DialogTitle>
        <DialogContent>
          <DialogContentText id="delete-dialog-description">
            Are you sure you want to delete the coupon <strong>{couponToDelete?.code}</strong>? 
            This action cannot be undone.
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelDelete}>Cancel</Button>
          <Button 
            onClick={handleConfirmDelete} 
            color="error" 
            variant="contained"
            autoFocus
            disabled={deleteCoupon.isLoading}
          >
            {deleteCoupon.isLoading ? (
              <CircularProgress size={24} sx={{ mr: 1 }} />
            ) : null}
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AdminCouponsPage;