"use client";

import Grid from "@mui/material/Grid";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Typography from "@mui/material/Typography";
import React, { FocusEvent, KeyboardEvent, PointerEvent, useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import TextField from "@mui/material/TextField";
import FormControl from "@mui/material/FormControl";
import InputLabel from "@mui/material/InputLabel";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import MenuItem from "@mui/material/MenuItem";
import CardActions from "@mui/material/CardActions";
import Button from "@mui/material/Button";
import RestartAlt from "@mui/icons-material/RestartAlt";
import Search from "@mui/icons-material/Search";
import FileDownload from "@mui/icons-material/FileDownload";
import dayjs from "dayjs";
import "dayjs/locale/zh-hk";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { Box, FormHelperText } from "@mui/material";
import { InputAdornment, NumberInput } from "../utils/numberInput";

interface BaseCriterion<T extends string> {
  label: string;
  label2?: string;
  paramName: T;
  paramName2?: T;
}

interface TextCriterion<T extends string> extends BaseCriterion<T> {
  type: "text";
  textType?: React.HTMLInputTypeAttribute;
  error?: boolean;
  helperText?: React.ReactNode;
}

interface SelectCriterion<T extends string> extends BaseCriterion<T> {
  type: "select";
  options: string[];
  needAll?: boolean;
}

interface DateRangeCriterion<T extends string> extends BaseCriterion<T> {
  type: "dateRange";
  needMonth?: boolean;
}

interface MonthYearCriterion<T extends string> extends BaseCriterion<T> {
  type: "monthYear";
}

interface NumberCriterion<T extends string> extends BaseCriterion<T> {
  type: "number";
}

export type Criterion<T extends string> =
  | TextCriterion<T>
  | SelectCriterion<T>
  | DateRangeCriterion<T>
  | MonthYearCriterion<T>
  | NumberCriterion<T>;

interface Props<T extends string> {
  criteria: Criterion<T>[];
  onSearch: (inputs: Record<T, string>) => void;
  onReset?: () => void;
  formType?: String;
}

function SearchBox<T extends string>({
  criteria,
  onSearch,
  onReset,
  formType,
}: Props<T>) {
  const { t } = useTranslation("common");
  const defaultInputs = useMemo(
    () =>
      criteria.reduce<Record<T, string>>(
        (acc, c) => {
          return {
            ...acc,
            [c.paramName]:
              c.type === "select"
                ? !(c.needAll === false)
                  ? "All"
                  : c.options.length > 0
                    ? c.options[0]
                    : ""
                : "",
          };
        },
        {} as Record<T, string>
      ),
    [criteria]
  );
  const [inputs, setInputs] = useState(defaultInputs);
  
  const makeInputChangeHandler = useCallback(
    (paramName: T): React.ChangeEventHandler<HTMLInputElement> => {
      return (e) => {
        setInputs((i) => ({ ...i, [paramName]: e.target.value }));
      };
    },
    []
  );
  
  const makeNumberChangeHandler = useCallback(
    (paramName: T): (event: FocusEvent<HTMLInputElement, Element> | PointerEvent<Element> | KeyboardEvent<Element>, value: number | null) => void => {
      return (event, value) => {
        setInputs((i) => ({ ...i, [paramName]: value }));
      };
    },
    []
  );

  const makeSelectChangeHandler = useCallback((paramName: T) => {
    return (e: SelectChangeEvent) => {
      setInputs((i) => ({ ...i, [paramName]: e.target.value }));
    };
  }, []);

  const makeDateChangeHandler = useCallback((paramName: T, needMonth?: boolean) => {
    return (e: any) => {
      if(needMonth){
        setInputs((i) => ({ ...i, [paramName]: dayjs(e).format("YYYY-MM") }));
      }else{
        setInputs((i) => ({ ...i, [paramName]: dayjs(e).format("YYYY-MM-DD") }));
      }
      
    };
  }, []);

  const makeMonthYearChangeHandler = useCallback((paramName: T) => {
    return (e: any) => {
      console.log(dayjs(e).format("YYYY-MM"));
      setInputs((i) => ({ ...i, [paramName]: dayjs(e).format("YYYY-MM") }));
    };
  }, []);

  const makeDateToChangeHandler = useCallback((paramName: T, needMonth?: boolean) => {
    return (e: any) => {
      if(needMonth){
      setInputs((i) => ({
        ...i,
        [paramName + "To"]: dayjs(e).format("YYYY-MM"),
      }));
    }else{
      setInputs((i) => ({
        ...i,
        [paramName + "To"]: dayjs(e).format("YYYY-MM-DD"),
      }));
    }
    };
  }, []);

  const handleReset = () => {
    setInputs(defaultInputs);
    onReset?.();
  };

  const handleSearch = () => {
    onSearch(inputs);
  };

  return (
    <Card>
      <CardContent sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
        <Typography variant="overline">{t("Search Criteria")}</Typography>
        <Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
          {criteria.map((c) => {
            return (
              <Grid key={c.paramName} item xs={6}>
                {c.type === "text" && (
                  <TextField
                    label={c.label}
                    type={c.textType ?? "text"}
                    fullWidth
                    onChange={makeInputChangeHandler(c.paramName)}
                    value={inputs[c.paramName]}
                    error={Boolean(c.error)}
                    helperText={Boolean(c.error) && c.helperText}
                  />
                )}
                {c.type === "select" && (
                  <FormControl fullWidth>
                    <InputLabel>{c.label}</InputLabel>
                    <Select
                      label={c.label}
                      onChange={makeSelectChangeHandler(c.paramName)}
                      value={inputs[c.paramName]}
                    >
                      {!(c.needAll === false) && (
                        <MenuItem value={"All"}>{t("All")}</MenuItem>
                      )}
                      {c.options.map((option, index) => (
                        <MenuItem key={`${option}-${index}`} value={option}>
                          {t(option)}
                        </MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                )}
                {c.type === "number" && (
                  <NumberInput 
                  placeholder={c.label}
                    min={50}
                    max={99}
                    onChange={makeNumberChangeHandler(c.paramName)}
                    endAdornment={<InputAdornment>%</InputAdornment>}
                  />
                )}
                {c.type === "monthYear" && (
                  <LocalizationProvider
                    dateAdapter={AdapterDayjs}
                    // TODO: Should maybe use a custom adapterLocale here to support YYYY-MM-DD
                    adapterLocale="zh-hk"
                  >
                    <Box display="flex">
                      <FormControl fullWidth>
                        <DatePicker
                            label={c.label}
                            onChange={makeMonthYearChangeHandler(c.paramName)}
                            value={
                              inputs[c.paramName]
                                ? dayjs(inputs[c.paramName])
                                : dayjs()
                            }
                            views={["month","year"]}
                          />
                      </FormControl>
                    </Box>
                  </LocalizationProvider>
                )}
                {c.type === "dateRange" && (
                  <LocalizationProvider
                    dateAdapter={AdapterDayjs}
                    // TODO: Should maybe use a custom adapterLocale here to support YYYY-MM-DD
                    adapterLocale="zh-hk"
                  >
                    <Box display="flex">
                      <FormControl fullWidth>
                        <DatePicker
                          label={c.label}
                          onChange={makeDateChangeHandler(c.paramName, c.needMonth)}
                          value={
                            inputs[c.paramName]
                              ? dayjs(inputs[c.paramName])
                              : null
                          }
                          views={c.needMonth ? ["month", "year"] : ["day", "month", "year"]}
                        />
                      </FormControl>
                      <Box
                        display="flex"
                        alignItems="center"
                        justifyContent="center"
                        marginInline={2}
                      >
                        {"-"}
                      </Box>
                      <FormControl fullWidth>
                        <DatePicker
                          label={c.label2}
                          onChange={makeDateToChangeHandler(c.paramName, c.needMonth)}
                          value={
                            inputs[c.paramName.concat("To") as T]
                              ? dayjs(inputs[c.paramName.concat("To") as T])
                              : null
                          }
                          views={c.needMonth ? ["month", "year"] : ["day", "month", "year"]}
                        />
                      </FormControl>
                    </Box>
                  </LocalizationProvider>
                )}
              </Grid>
            );
          })}
        </Grid>
        <CardActions sx={{ justifyContent: "flex-end" }}>
          <Button
            variant="text"
            startIcon={<RestartAlt />}
            onClick={handleReset}
          >
            {t("Reset")}
          </Button>
          <Button
            variant="outlined"
            startIcon={
              (formType === "download" && <FileDownload />) || <Search />
            }
            onClick={handleSearch}
          >
            {(formType === "download" && t("Download")) || t("Search")}
          </Button>
        </CardActions>
      </CardContent>
    </Card>
  );
}

export default SearchBox;
