import React, { useState, useEffect, useRef } from "react";
import {
  Box,
  Typography,
  Card,
  Grid,
  IconButton,
  Popover,
  TextField,
} from "@mui/material";
import {
  ChevronLeft,
  ChevronRight,
  CalendarMonthOutlined,
} from "@mui/icons-material";
import PersianDate from "persian-date";
import moment from "moment";

const MonthlyDataCalendar = ({
  onDateSelect,
  dayData = {},
  selectedDate = null,
  label = "انتخاب تاریخ",
  className = "",
  disableToday = false,
  maxGregorianDate = null,
  customDateFilter = null,
}) => {
  const [currentMonth, setCurrentMonth] = useState(new PersianDate());
  const [calendarDays, setCalendarDays] = useState([]);
  const [anchorEl, setAnchorEl] = useState(null);
  const inputRef = useRef(null);

  const open = Boolean(anchorEl);

  const handleClick = () => {
    setAnchorEl(inputRef.current);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  // Get Persian month names
  const monthNames = [
    "فروردین",
    "اردیبهشت",
    "خرداد",
    "تیر",
    "مرداد",
    "شهریور",
    "مهر",
    "آبان",
    "آذر",
    "دی",
    "بهمن",
    "اسفند",
  ];

  const dayNames = ["ش", "ی", "د", "س", "چ", "پ", "ج"];

  const getDayData = (formattedDate) => {
    return dayData[formattedDate] || null;
  };

  const isDateEnabled = (date) => {
    const dateStr = date.format("YYYY/MM/DD");

    if (customDateFilter) {
      return customDateFilter(date, dateStr, dayData);
    }

    const today = new PersianDate();
    const twoDaysAgo = new PersianDate().subtract("day", 2);
    const oneDayAgo = new PersianDate().subtract("day", 1);

    const todayStr = today.format("YYYY/MM/DD");
    const twoDaysAgoStr = twoDaysAgo.format("YYYY/MM/DD");
    const oneDayAgoStr = oneDayAgo.format("YYYY/MM/DD");

    const isTodayAllowed = disableToday ? false : dateStr === todayStr;

    let isAfterMax = false;
    if (maxGregorianDate) {
      const gregorianOfCell = date.toDate ? date.toDate() : new Date();
      isAfterMax = moment(gregorianOfCell).isAfter(
        moment(maxGregorianDate),
        "day"
      );
    }

    const hasData = dayData[dateStr] !== undefined;
    const isActive =
      hasData &&
      (dayData[dateStr].active === undefined ||
        dayData[dateStr].active === true);

    return (
      !isAfterMax &&
      (isTodayAllowed ||
        dateStr === twoDaysAgoStr ||
        dateStr === oneDayAgoStr ||
        isActive)
    );
  };

  useEffect(() => {
    const generateCalendar = () => {
      const days = [];
      const year = currentMonth.year();
      const month = currentMonth.month();
      const daysInMonth = currentMonth.daysInMonth();

      const firstDayOfMonth = new PersianDate([year, month, 1]);
      let dayOfWeek = firstDayOfMonth.day();
      if (dayOfWeek >= 1 && dayOfWeek <= 7) {
        dayOfWeek = dayOfWeek - 1;
      }
      dayOfWeek = dayOfWeek % 7;

      for (let i = 0; i < dayOfWeek; i++) {
        days.push(null);
      }

      for (let day = 1; day <= daysInMonth; day++) {
        const date = new PersianDate([year, month, day]);
        const today = new PersianDate();
        const isEnabled = isDateEnabled(date);
        const formattedDate = date.format("YYYY/MM/DD");
        const data = getDayData(formattedDate);
        const hasZeroValue = isEnabled && data && data.value1 === 0;

        days.push({
          date: date,
          day: day,
          formattedDate: formattedDate,
          isToday:
            date.year() === today.year() &&
            date.month() === today.month() &&
            date.date() === today.date(),
          isEnabled: isEnabled,
          hasZeroValue: hasZeroValue,
        });
      }

      setCalendarDays(days);
    };

    generateCalendar();
  }, [currentMonth, dayData]);

  const handleDayClick = (dayInfo) => {
    if (dayInfo && dayInfo.isEnabled && !dayInfo.hasZeroValue && onDateSelect) {
      onDateSelect(dayInfo);
      handleClose();
    }
  };

  const handleNextMonth = () => {
    const nextMonth = new PersianDate([
      currentMonth.year(),
      currentMonth.month() + 1,
      1,
    ]);
    setCurrentMonth(nextMonth);
  };

  const handlePrevMonth = () => {
    const prevMonth = new PersianDate([
      currentMonth.year(),
      currentMonth.month() - 1,
      1,
    ]);
    setCurrentMonth(prevMonth);
  };

  const isSelected = (formattedDate) => {
    return selectedDate && selectedDate === formattedDate;
  };

  const formatNumber = (num) => {
    if (num === null || num === undefined) return "";
    return num.toLocaleString("fa-IR");
  };

  const getDisplayValue = () => {
    if (!selectedDate) return "";
    const dayInfo = calendarDays.find(
      (d) => d && d.formattedDate === selectedDate
    );
    return dayInfo
      ? `${dayInfo.day.toLocaleString("fa-IR")} ${
          monthNames[dayInfo.date.month() - 1]
        }`
      : selectedDate;
  };

  return (
    <Box className={className} sx={{ width: "100%" }}>
      <TextField
        ref={inputRef}
        fullWidth
        value={getDisplayValue()}
        onClick={handleClick}
        label={label}
        placeholder="انتخاب تاریخ..."
        size="medium"
        InputProps={{
          readOnly: true,
          startAdornment: (
            <IconButton size="small" onClick={handleClick}>
              <CalendarMonthOutlined fontSize="small" />
            </IconButton>
          ),
        }}
        sx={{
          cursor: "pointer",
          width: "100%",
          fontSize: { xs: "13px", sm: "16px" },
        }}
      />

      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "left",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <Card
          elevation={3}
          sx={{
            p: { xs: 1, sm: 2 },
            borderRadius: 3,
            backgroundColor: "#fff",
            maxWidth: 500,
            width: "99%",
          }}
        >
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              mb: { xs: 1, sm: 2 },
              pb: { xs: 1, sm: 2 },
              borderBottom: "2px solid #f0f0f0",
            }}
          >
            <IconButton onClick={handlePrevMonth} size="small">
              <ChevronRight />
            </IconButton>

            <Typography
              variant="h6"
              sx={{
                fontWeight: "bold",
                color: "#333",
                fontSize: { xs: "16px", sm: "20px" },
              }}
            >
              {monthNames[currentMonth.month() - 1]} {currentMonth.year()}
            </Typography>

            <IconButton onClick={handleNextMonth} size="small">
              <ChevronLeft />
            </IconButton>
          </Box>

          <Grid
            container
            spacing={{ xs: 0.5, sm: 1 }}
            sx={{ mb: { xs: 0.5, sm: 1 } }}
          >
            {dayNames.map((dayName, index) => (
              <Grid item xs={12 / 7.3} key={index}>
                <Box
                  sx={{
                    textAlign: "center",
                    fontWeight: "bold",
                    color: "#666",
                    fontSize: { xs: "12px", sm: "14px" },
                    py: { xs: 0.5, sm: 1 },
                  }}
                >
                  {dayName}
                </Box>
              </Grid>
            ))}
          </Grid>

          <Grid container spacing={{ xs: 0.5, sm: 1 }}>
            {calendarDays.map((dayInfo, index) => {
              if (!dayInfo) {
                // Empty cell
                return (
                  <Grid item xs={12 / 7.3} key={`empty-${index}`}>
                    <Box sx={{ aspectRatio: "1/1" }} />
                  </Grid>
                );
              }

              const data = getDayData(dayInfo.formattedDate);
              const isSelectedDay = isSelected(dayInfo.formattedDate);

              let bgColor = "#fff";
              let borderColor = "#e0e0e0";
              let opacity = 1;
              let cursorStyle = "pointer";

              if (!dayInfo.isEnabled || dayInfo.hasZeroValue) {
                bgColor = "#f5f5f5";
                borderColor = "#d0d0d0";
                opacity = dayInfo.hasZeroValue ? 0.4 : 0.25;
                cursorStyle = "not-allowed";
              } else if (isSelectedDay) {
                bgColor = "#e3f2fd";
                borderColor = "#1976d2";
              }

              if (
                dayInfo.isToday &&
                dayInfo.isEnabled &&
                !dayInfo.hasZeroValue
              ) {
                borderColor = "#ff9800";
              }

              return (
                <Grid item xs={12 / 7.3} key={index}>
                  <Card
                    onClick={() => handleDayClick(dayInfo)}
                    sx={{
                      aspectRatio: "1/1",
                      cursor: cursorStyle,
                      transition: "all 0.2s ease",
                      backgroundColor: bgColor,
                      border: {
                        xs: `1.5px solid ${borderColor}`,
                        sm: `2px solid ${borderColor}`,
                      },
                      display: "flex",
                      flexDirection: "column",
                      alignItems: "center",
                      justifyContent: "center",
                      p: { xs: 0.5, sm: 1 },
                      gap: { xs: 0.25, sm: 0.5 },
                      opacity: opacity,
                      "&:hover":
                        dayInfo.isEnabled && !dayInfo.hasZeroValue
                          ? {
                              transform: "scale(1.05)",
                              boxShadow: "0 4px 12px rgba(0,0,0,0.15)",
                              backgroundColor: "#f5f5f5",
                            }
                          : {},
                    }}
                  >
                    <Typography
                      variant="body1"
                      sx={{
                        fontWeight: "bold",
                        fontSize: { xs: "16px", sm: "20px" },
                        color: dayInfo.isToday ? "#ff9800" : "#333",
                        lineHeight: 1.2,
                      }}
                    >
                      {dayInfo.day.toLocaleString("fa-IR")}
                    </Typography>

                    {data && data.value1 !== undefined && (
                      <Typography
                        variant="caption"
                        sx={{
                          fontSize: { xs: "10px", sm: "13px" },
                          color: "#1976d2",
                          fontWeight: "600",
                          lineHeight: 1.2,
                        }}
                      >
                        {formatNumber(data.value1)}
                      </Typography>
                    )}
                  </Card>
                </Grid>
              );
            })}
          </Grid>
        </Card>
      </Popover>
    </Box>
  );
};

export default MonthlyDataCalendar;
