import Button from "@mui/material/Button";
import Checkbox from "@mui/material/Checkbox";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import ListItemText from "@mui/material/ListItemText";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { AppJumpConfigField } from "@/shared/ui/AppJumpConfigField.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { ExternalImageUploadField } from "../shared/ExternalImageUploadField.jsx";
import { useExternalI18n } from "../i18n/ExternalI18nProvider.jsx";

const displayScopeOptions = [
  ["home", "banners.scopeHome"],
  ["room", "banners.scopeRoom"],
  ["recharge", "banners.scopeRecharge"],
  ["me", "banners.scopeMe"]
];

export function BannerCreateDialog({ loading, onClose, onSubmit, open }) {
  const { direction, locale, t } = useExternalI18n();
  const [form, setForm] = useState(initialForm);
  useEffect(() => setForm(initialForm), [open]);

  const submit = (event) => {
    event.preventDefault();
    onSubmit({
      ...form,
      regionId: Number(form.regionId || 0),
      roomSmallImageUrl: form.displayScopes.includes("room") ? form.roomSmallImageUrl : "",
      sortOrder: Number(form.sortOrder || 0)
    });
  };

  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={loading ? undefined : onClose}>
      <Stack component="form" onSubmit={submit}>
        <DialogTitle>{t("banners.create")}</DialogTitle>
        <DialogContent>
          <Stack className="external-dialog-fields" spacing={2}>
            <ExternalImageUploadField disabled={loading} label={t("banners.image")} value={form.coverUrl} onChange={(coverUrl) => setForm({ ...form, coverUrl })} />
            {form.displayScopes.includes("room") ? <ExternalImageUploadField disabled={loading} label={t("banners.roomImage")} value={form.roomSmallImageUrl} onChange={(roomSmallImageUrl) => setForm({ ...form, roomSmallImageUrl })} /> : null}
            <TextField disabled={loading} label={t("banners.platform")} required select value={form.platform} onChange={(event) => setForm({ ...form, platform: event.target.value })}>
              <MenuItem value="android">Android</MenuItem>
              <MenuItem value="ios">iOS</MenuItem>
            </TextField>
            <TextField disabled={loading} label={t("banners.description")} slotProps={{ htmlInput: { maxLength: 255 } }} value={form.description} onChange={(event) => setForm({ ...form, description: event.target.value })} />
            <AppJumpConfigField
              allowCustom
              appParamLabel={t("banners.appParam")}
              disabled={loading}
              h5Label={t("banners.h5Param")}
              messages={appJumpMessages(t)}
              paramValue={form.param}
              required
              showHint={false}
              typeLabel={t("banners.jumpType")}
              typeValue={form.bannerType}
              onChange={({ param, type }) => setForm({ ...form, bannerType: type, param })}
            />
            <TextField
              disabled={loading}
              label={t("banners.displayScope")}
              required
              select
              slotProps={{ select: { multiple: true, renderValue: (selected) => selected.map((value) => t(displayScopeOptions.find(([key]) => key === value)?.[1]) || value).join(", ") } }}
              value={form.displayScopes}
              onChange={(event) => setForm({ ...form, displayScopes: typeof event.target.value === "string" ? event.target.value.split(",") : event.target.value })}
            >
              {displayScopeOptions.map(([value, labelKey]) => <MenuItem key={value} value={value}><Checkbox checked={form.displayScopes.includes(value)} /><ListItemText primary={t(labelKey)} /></MenuItem>)}
            </TextField>
            <Stack direction={{ xs: "column", sm: "row" }} spacing={1.5}>
              <TextField disabled={loading} label={t("banners.regionId")} slotProps={{ htmlInput: { min: 0 } }} type="number" value={form.regionId} onChange={(event) => setForm({ ...form, regionId: event.target.value })} />
              <TextField disabled={loading} helperText={t("banners.countryCodeHint")} label={t("banners.countryCode")} value={form.countryCode} onChange={(event) => setForm({ ...form, countryCode: event.target.value.toUpperCase() })} />
              <TextField disabled={loading} label={t("banners.sort")} slotProps={{ htmlInput: { min: 0 } }} type="number" value={form.sortOrder} onChange={(event) => setForm({ ...form, sortOrder: event.target.value })} />
            </Stack>
            <TimeRangeFilter
              direction={direction}
              disabled={loading}
              label={t("banners.schedule")}
              locale={locale}
              messages={timeRangeMessages(t)}
              value={{ endMs: form.endsAtMs, startMs: form.startsAtMs }}
              onChange={({ endMs, startMs }) => setForm({ ...form, endsAtMs: endMs, startsAtMs: startMs })}
            />
            <TextField disabled={loading} label={t("common.status")} select value={form.status} onChange={(event) => setForm({ ...form, status: event.target.value })}>
              <MenuItem value="active">{t("common.enabled")}</MenuItem>
              <MenuItem value="disabled">{t("common.disabled")}</MenuItem>
              <MenuItem value="expired">{t("common.expired")}</MenuItem>
            </TextField>
          </Stack>
        </DialogContent>
        <DialogActions><Button disabled={loading} onClick={onClose}>{t("common.cancel")}</Button><Button disabled={loading || !form.coverUrl} type="submit" variant="contained">{t("common.create")}</Button></DialogActions>
      </Stack>
    </Dialog>
  );
}

const initialForm = {
  bannerType: "h5",
  countryCode: "",
  coverUrl: "",
  description: "",
  displayScopes: ["home"],
  endsAtMs: 0,
  param: "",
  platform: "android",
  regionId: "",
  roomSmallImageUrl: "",
  sortOrder: "0",
  startsAtMs: 0,
  status: "active"
};

function appJumpMessages(t) {
  return {
    appTarget: t("jump.appTarget"),
    gameId: t("jump.gameId"),
    giftId: t("jump.giftId"),
    redPacketNo: t("jump.redPacketNo"),
    roomId: t("jump.roomId"),
    targets: Object.fromEntries(["wallet", "room", "room_random", "room_window", "room_random_window", "room_game", "room_random_game", "explore_game", "custom"].map((value) => [value, t(`jump.target.${value}`)])),
    window: t("jump.window"),
    windows: Object.fromEntries(["game_window", "gift_panel", "red_packet_claim", "wheel"].map((value) => [value, t(`jump.window.${value}`)]))
  };
}

function timeRangeMessages(t) {
  return Object.fromEntries([
    "apply", "clear", "completeRange", "duration", "durationDays", "durationHours", "durationMinutes", "end", "endAfterStart", "endDate", "endDateAfterStart", "endDateLaterShort", "endLaterShort", "endMark", "hour", "lessMinute", "minute", "nextMonth", "pending", "previousMonth", "quickDay", "quickHour", "quickWeek", "sameDay", "start", "startDate", "startMark", "unlimited"
  ].map((key) => [key, t(`time.${key}`)]));
}
