"use client";

import { useState, type MouseEvent } from "react";

import AccessTimeOutlinedIcon from "@mui/icons-material/AccessTimeOutlined";
import ExpandLessRoundedIcon from "@mui/icons-material/ExpandLessRounded";
import ExpandMoreRoundedIcon from "@mui/icons-material/ExpandMoreRounded";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Popover from "@mui/material/Popover";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import type { SxProps, Theme } from "@mui/material/styles";

import {
  adjustMeetingTime,
  meetingTimeToParts,
  timePartsToMeetingValue,
  type MeetingTimeParts,
} from "../meeting-create-form";

type MeetingTimePickerProps = {
  value: string;
  onChange: (value: string) => void;
  error?: boolean;
  helperText?: string;
  inputSx?: SxProps<Theme>;
};

function TimeSection({
  value,
  onIncrease,
  onDecrease,
}: {
  value: string;
  onIncrease: () => void;
  onDecrease: () => void;
}) {
  return (
    <Box sx={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
      <IconButton
        size="small"
        aria-label={`Increase ${value}`}
        onClick={onIncrease}
        sx={{ width: 36, height: 36, color: "#454545" }}
      >
        <ExpandLessRoundedIcon />
      </IconButton>

      <Typography sx={{ my: 0.5, color: "#454545", fontSize: 18 }}>
        {value}
      </Typography>

      <IconButton
        size="small"
        aria-label={`Decrease ${value}`}
        onClick={onDecrease}
        sx={{ width: 36, height: 36, color: "#454545" }}
      >
        <ExpandMoreRoundedIcon />
      </IconButton>
    </Box>
  );
}

function formatDisplayValue(value: string) {
  if (!value) return "";

  const parts = meetingTimeToParts(value);
  return `${String(parts.hour).padStart(2, "0")}:${String(parts.minute).padStart(2, "0")} ${parts.period}`;
}

export function MeetingTimePicker({
  value,
  onChange,
  error = false,
  helperText,
  inputSx,
}: MeetingTimePickerProps) {
  const [anchorElement, setAnchorElement] = useState<HTMLElement | null>(null);
  const [draftTime, setDraftTime] = useState<MeetingTimeParts>(() =>
    meetingTimeToParts(value),
  );

  const handleOpen = (event: MouseEvent<HTMLElement>) => {
    setDraftTime(meetingTimeToParts(value));
    setAnchorElement(event.currentTarget);
  };

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

  const updateDraft = (
    section: "hour" | "minute",
    amount: number,
  ) => {
    setDraftTime((current) =>
      adjustMeetingTime(current, section, amount),
    );
  };

  const handleConfirm = () => {
    onChange(timePartsToMeetingValue(draftTime));
    handleClose();
  };

  return (
    <>
      <TextField
        fullWidth
        value={formatDisplayValue(value)}
        placeholder="Select time"
        onClick={handleOpen}
        error={error}
        helperText={helperText}
        slotProps={{
          htmlInput: {
            readOnly: true,
            "aria-label": "Select time",
          },
          input: {
            startAdornment: (
              <InputAdornment position="start">
                <AccessTimeOutlinedIcon
                  sx={{ fontSize: 18, color: "text.secondary" }}
                />
              </InputAdornment>
            ),
          },
        }}
        sx={{
          ...inputSx,
          cursor: "pointer",
          "& .MuiInputBase-input": {
            cursor: "pointer",
            fontSize: 12,
          },
        }}
      />

      <Popover
        open={Boolean(anchorElement)}
        anchorEl={anchorElement}
        onClose={handleClose}
        anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
        transformOrigin={{ vertical: "top", horizontal: "left" }}
        sx={{ zIndex: 1700 }}
        slotProps={{
          paper: {
            sx: {
              width: 256,
              mt: 0.75,
              borderRadius: "15px",
              boxShadow: "0 4px 10px rgba(0, 0, 0, 0.17)",
              overflow: "hidden",
            },
          },
        }}
      >
        <Box sx={{ px: 3, pt: 1.25, pb: 1.5 }}>
          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <Box sx={{ display: "flex", alignItems: "center", gap: 1.25 }}>
              <TimeSection
                value={String(draftTime.hour).padStart(2, "0")}
                onIncrease={() => updateDraft("hour", 1)}
                onDecrease={() => updateDraft("hour", -1)}
              />

              <Typography sx={{ color: "#454545", fontSize: 18 }}>
                :
              </Typography>

              <TimeSection
                value={String(draftTime.minute).padStart(2, "0")}
                onIncrease={() => updateDraft("minute", 5)}
                onDecrease={() => updateDraft("minute", -5)}
              />
            </Box>

            <Button
              onClick={() =>
                setDraftTime((current) => ({
                  ...current,
                  period: current.period === "AM" ? "PM" : "AM",
                }))
              }
              sx={{
                minWidth: 44,
                height: 36,
                borderRadius: "18px",
                color: "#454545",
                fontSize: 18,
                fontWeight: 400,
                textTransform: "none",
              }}
            >
              {draftTime.period}
            </Button>
          </Box>

          <Box sx={{ mt: 1.25, display: "flex", justifyContent: "center", gap: 1 }}>
            <Button
              variant="outlined"
              onClick={handleClose}
              sx={{
                width: 86,
                height: 28,
                borderColor: "#d5d7da",
                borderRadius: "6px",
                color: "#181d27",
                fontSize: 12,
                textTransform: "none",
              }}
            >
              Cancel
            </Button>

            <Button
              variant="contained"
              onClick={handleConfirm}
              sx={{
                width: 86,
                height: 28,
                borderRadius: "6px",
                bgcolor: "#1a64a8",
                boxShadow: "none",
                fontSize: 12,
                textTransform: "none",
                "&:hover": { bgcolor: "#155489", boxShadow: "none" },
              }}
            >
              Confirm
            </Button>
          </Box>
        </Box>
      </Popover>
    </>
  );
}
