import * as React from 'react';
import { CardMedia, Chip, Grid, IconButton, Modal, Tooltip, useTheme } from '@mui/material';
import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Eye } from '@phosphor-icons/react';
import { Clock as ClockIcon } from '@phosphor-icons/react/dist/ssr/Clock';
import { Download as DownloadIcon } from '@phosphor-icons/react/dist/ssr/Download';
import dayjs from 'dayjs';
import ReactImageMagnify from 'react-image-magnify';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';

import { Close } from '@mui/icons-material';

import { getProductColorCss } from '@/utils/product-color';
import { getPrimaryProductImage } from '@/utils/product-image';

interface ProductImageData {
  _id: string;
  fileName: string;
  fileType: string;
  isDeleted: boolean;
  createdAt: string;
  updatedAt: string;
  fileUrl: string;
  thumbnail: string | null;
}

interface Product {
  _id: string;
  productName: string;
  productDescription: string;
  quantity: number;
  price: number;
  colors: string[];
  sizes: string[];
  createdAt: string;
  productImageData: ProductImageData[];
  categoryName: string;
}

export interface ProductCardProps {
  product: Product;
  totalProducts?: number;
  displayImageUrl?: string;
  onEdit?: (product: Product) => void;
  onDelete?: (product: Product) => void;
  onDetail?: (product: Product) => void;
}

const mediaUrl = process.env.NEXT_PUBLIC_LIVE_API_URL;

const boxStyle = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: '90%',
  maxWidth: 1200,
  maxHeight: '90vh',
  bgcolor: 'background.paper',
  border: 'none',
  outline: 'none',
  boxShadow: 24,
  p: 4,
  borderRadius: '25px',
  overflowY: 'auto',
};

export function ProductsCard({ product, displayImageUrl, onEdit, onDelete, onDetail }: ProductCardProps): React.JSX.Element {
  const [open, setOpen] = React.useState(false);
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
  const menuOpen = Boolean(anchorEl);
  const theme = useTheme();
  const productImageUrl = displayImageUrl ?? getPrimaryProductImage(product.productImageData)?.fileUrl ?? '';

  const handleClose = () => {
    setOpen(false);
  };

  const handleMenuClick = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
  };
  const handleMenuClose = () => {
    setAnchorEl(null);
  };
  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation();
    handleMenuClose();
    if (onEdit) onEdit(product);
  };
  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    handleMenuClose();
    if (onDelete) onDelete(product);
  };
  const handleCardClick = (e: React.MouseEvent) => {
    if (!menuOpen && onDetail) {
      onDetail(product);
    }
  };

  const uniqueColors = Array.from(new Set(product.colors));
  const uniqueSizes = Array.from(new Set(product.sizes));

  return (
    <>
      <Tooltip title={product.productName}>
        <Card sx={{ cursor: 'pointer', position: 'relative' }} onClick={handleCardClick}>
          {productImageUrl ? (
            <CardMedia
              key={productImageUrl}
              sx={{ height: 180 }}
              image={productImageUrl}
              title={product.productName}
            />
          ) : (
            <Box
              sx={{
                height: 180,
                bgcolor: theme.palette.mode === 'dark' ? 'rgba(51, 65, 85, 0.5)' : 'action.hover',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Typography variant="caption" color="text.secondary">
                No image
              </Typography>
            </Box>
          )}
          <IconButton
            size="small"
            onClick={handleMenuClick}
            sx={{
              position: 'absolute',
              top: 12,
              right: 12,
              bgcolor: theme.palette.mode === 'dark'
                ? 'rgba(30, 41, 59, 0.85)'
                : 'rgba(255,255,255,0.85)',
              '&:hover': {
                bgcolor: theme.palette.mode === 'dark' ? '#475569' : 'grey.200',
              },
              zIndex: 3,
              boxShadow: 1,
            }}
          >
            <MoreVertIcon />
          </IconButton>
          <Menu
            anchorEl={anchorEl}
            open={menuOpen}
            onClose={handleMenuClose}
            transformOrigin={{ horizontal: 'right', vertical: 'top' }}
            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          >
            <MenuItem
              onClick={(e) => {
                e.stopPropagation();
                handleMenuClose();
                if (onDetail) onDetail(product);
              }}
            >
              View Details
            </MenuItem>
            <MenuItem onClick={handleEdit}>Edit</MenuItem>
            <MenuItem onClick={handleDelete} sx={{ color: 'error.main' }}>
              Delete
            </MenuItem>
          </Menu>
          <CardContent sx={{ overflow: 'hidden', p: '10px' }}>
            <Typography gutterBottom variant="h6" component="div" color="text.primary">
              {product.productName.length > 20 ? product.productName.slice(0, 20) + '...' : product.productName}
            </Typography>
            <Stack gap={1}>
              <Stack direction={'row'} gap={1} alignItems={'center'}>
                <Typography variant="caption" color={'text.secondary'}>
                  Category:
                </Typography>
                <Typography variant="subtitle2" color="text.primary">{product.categoryName}</Typography>
              </Stack>
              <Stack direction={'row'} gap={1} alignItems={'center'}>
                <Typography variant="caption" color={'text.secondary'}>
                  Size:
                </Typography>
                <Chip
                  label={
                    product.sizes[0] === 'small'
                      ? 'S'
                      : product.sizes[0] === 'medium'
                        ? 'M'
                        : product.sizes[0] === 'large'
                          ? 'L'
                          : product.sizes[0] === 'extralarge'
                            ? 'XL'
                            : ''
                  }
                  size="small"
                  variant="outlined"
                  color="primary"
                />
                <Typography variant="subtitle2"></Typography>
              </Stack>
              <Stack direction={'row'} gap={1} alignItems={'center'}>
                <Typography variant="caption" color={'text.secondary'}>
                  Color:
                </Typography>
                <div
                  style={{
                    borderRadius: '50%',
                    width: '20px',
                    height: '20px',
                    backgroundColor: getProductColorCss(product.colors[0]),
                    border: theme.palette.mode === 'dark' ? '1px solid #475569' : '1px solid #e5e7eb',
                  }}
                />
                <Typography variant="subtitle2"></Typography>
              </Stack>
            </Stack>
          </CardContent>
          <Divider sx={{ width: '70%', margin: 'auto' }} />
          <Stack direction="row" spacing={2} sx={{ alignItems: 'center', justifyContent: 'space-between', p: 2 }}>
            <Stack sx={{ alignItems: 'center' }} direction="row" spacing={1}>
              <ClockIcon fontSize="var(--icon-fontSize-sm)" />
              <Typography color="text.secondary" display="inline" variant="body2">
                Created {dayjs(product.createdAt).format('MMM D, YYYY')}
              </Typography>
            </Stack>
            {/* <Stack sx={{ alignItems: 'center' }} direction="row" spacing={1}>
            <Tooltip title="Description">
              <Eye size={16} weight="fill" style={{ cursor: 'pointer' }} onClick={handleOpen} />
            </Tooltip>
          </Stack> */}
          </Stack>
        </Card>
      </Tooltip>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
        style={{ backdropFilter: 'blur(5px)' }}
      >
        <Box sx={boxStyle}>
          <IconButton
            onClick={handleClose}
            sx={{
              padding: '0px',
              position: 'absolute',
              right: '5px',
              top: '5px',
            }}
          >
            <Close sx={{ 
              cursor: 'pointer', 
              color: theme.palette.mode === 'dark' ? '#f87171' : 'red' 
            }} />
          </IconButton>
          <Grid container>
            <Grid lg={6}>
              {productImageUrl ? (
                <Stack p={1} border={'1px solid var(--mui-palette-primary-main)'}>
                  <ReactImageMagnify
                    smallImage={{
                      alt: product.productName,
                      isFluidWidth: true,
                      src: productImageUrl,
                      width: 500,
                      height: 500,
                    }}
                    largeImage={{
                      src: productImageUrl,
                      width: 1200,
                      height: 1800,
                    }}
                    isHintEnabled
                    shouldHideHintAfterFirstActivation={false}
                    enlargedImagePosition="over"
                  />
                </Stack>
              ) : (
                <Box
                  sx={{
                    height: 300,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    border: '1px dashed',
                    borderColor: 'divider',
                    borderRadius: 2,
                  }}
                >
                  <Typography color="text.secondary">No image available</Typography>
                </Box>
              )}
            </Grid>
            <Grid lg={6} p={2}>
              <Typography variant="h3" color="text.primary">{product.productName}</Typography>
              <Typography variant="h4" mt={1} color="success.main">${product.price}</Typography>
              <Stack gap={2} mt={3}>
                <Stack direction={'row'} gap={1} alignItems={'center'}>
                  <Typography variant="caption" color={'text.secondary'}>
                    Category:
                  </Typography>
                  <Typography variant="subtitle2" color="text.primary">{product.categoryName}</Typography>
                </Stack>
                <Stack direction={'row'} gap={1} alignItems={'center'}>
                  <Typography variant="caption" color={'text.secondary'}>
                    Quantity:
                  </Typography>
                  <Typography variant="subtitle2" color="text.primary">{product.quantity}</Typography>
                </Stack>
                <Stack direction={'row'} gap={1} alignItems={'center'}>
                  <Typography variant="caption" color={'text.secondary'}>
                    Size:
                  </Typography>
                  <Chip
                    label={
                      product.sizes[0] === 'small'
                        ? 'S'
                        : product.sizes[0] === 'medium'
                          ? 'M'
                          : product.sizes[0] === 'large'
                            ? 'L'
                            : product.sizes[0] === 'extralarge'
                              ? 'XL'
                              : ''
                    }
                    size="small"
                    variant="outlined"
                    color="primary"
                  />
                  <Typography variant="subtitle2"></Typography>
                </Stack>
                <Stack direction={'row'} gap={1} alignItems={'center'}>
                  <Typography variant="caption" color={'text.secondary'}>
                    Color:
                  </Typography>
                  <div
                    style={{
                      borderRadius: '50%',
                      width: '20px',
                      height: '20px',
                      backgroundColor: getProductColorCss(product.colors[0]),
                    }}
                  />
                  <Typography variant="subtitle2"></Typography>
                </Stack>
              </Stack>
              <Typography id="modal-modal-title" variant="h6" component="h1" sx={{ fontWeight: 'bold', mt: 2 }} color="text.primary">
                Product Description
              </Typography>
              <Typography
                id="modal-modal-description"
                variant="body1"
                sx={{
                  mt: 2,
                  color: 'text.secondary',
                  width: '100%',
                  maxWidth: '450px',
                  whiteSpace: 'normal',
                  wordBreak: 'break-word',
                }}
              >
                {product.productDescription}
              </Typography>
            </Grid>
          </Grid>
          {/* <Stack direction={'row'}>
            <Stack>
              
            </Stack>
            <Stack>Product Dwesc</Stack>
          </Stack> */}
        </Box>
      </Modal>
    </>
  );
}
