import Button from "@mui/joy/Button";
import Divider from "@mui/joy/Divider";
import FormControl from "@mui/joy/FormControl";
import FormLabel from "@mui/joy/FormLabel";
import Grid from "@mui/joy/Grid";
import Input from "@mui/joy/Input";
import Option from "@mui/joy/Option";
import Select from "@mui/joy/Select";
import Typography from "@mui/joy/Typography";
import { Box } from "@mui/joy";
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import useLocalization from "~/utils/useLocalization";
import type {
  Position,
  SelectedAsset,
  SetPositions,
} from "~/interfaces/simulator";

const splitDayMaxValueMap = {
  monthly: 31,
  quarterly: 93,
  biannualy: 186,
  yearly: 365,
  random: 3650,
};

type SplitByOptions =
  | "monthly"
  | "quarterly"
  | "biannualy"
  | "yearly"
  | "random";

const dividerTextSx = { typography: { xs: "body1", md: "h6" } };
const inputLabelSx = { fontSize: { xs: "xs", md: "sm" } };

type PartialPosition = {
  type: string;
  qtd: string;
  date: string;
};

interface AddPositionFormProps {
  positions: Position[];
  setPositions: SetPositions;
  selectedAsset: SelectedAsset;
}

export default function AddPositionForm({
  positions,
  setPositions,
  selectedAsset,
}: AddPositionFormProps) {
  const { localization } = useLocalization();

  const [qtdError, setQtdError] = useState(false);

  const [splitDayMaxValue, setSplitDayMaxValue] = useState(31);

  //const [splitDayDisabled, setSplitDayDisabled] = useState(false);

  const [dayText, setDayText] = useState(
    localization.body.assetModal.dayTextMap.monthly
  );

  const addPosition = (partialPosition: PartialPosition) => {
    const position: Position = {
      id: uuidv4(),
      ticker: selectedAsset.ticker,
      ...partialPosition,
    };
    if (!position.qtd) {
      setQtdError(true);
      return;
    }
    setPositions([...positions, position]);
    setQtdError(false);
  };

  return (
    <>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          // const total = parseInt(e.target[0].value);
          // const frequency = e.target[2].value;
          // const splitDayDelta = parseInt(e.target[3].value);
          // const splitByCount = parseInt(e.target[4].value);
          // console.log(total, frequency, splitDayDelta, splitByCount);
        }}
      >
        <Grid
          container
          spacing={1}
          direction='row'
          justifyContent='flex-start'
          alignItems='flex-end'
        >
          <Grid xs={5}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>
                {localization.body.assetModal.buyAmount}
              </FormLabel>
              <Input
                sx={inputLabelSx}
                type='number'
                name='total'
                disabled
                startDecorator='R$'
                slotProps={{
                  input: {
                    min: 0.0,
                  },
                }}
              />
            </FormControl>
          </Grid>
          <Grid xs={7}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>
                {localization.body.assetModal.frequency.title}
              </FormLabel>
              <Select
                defaultValue='monthly'
                name='frequency'
                sx={inputLabelSx}
                disabled
                onChange={(_, splitBy: SplitByOptions | null) => {
                  if (splitBy) {
                    setSplitDayMaxValue(splitDayMaxValueMap[splitBy]);
                    setDayText(
                      localization.body.assetModal.dayTextMap[splitBy]
                    );
                    // if (splitBy === "random") {
                    //   setSplitDayDisabled(true);
                    // } else {
                    //   setSplitDayDisabled(false);
                    // }
                  }
                }}
              >
                <Option sx={inputLabelSx} value='monthly'>
                  {localization.body.assetModal.frequency.monthly}
                </Option>
                <Option sx={inputLabelSx} value='quarterly'>
                  {localization.body.assetModal.frequency.quarterly}
                </Option>
                <Option sx={inputLabelSx} value='biannualy'>
                  {localization.body.assetModal.frequency.biannualy}
                </Option>
                <Option sx={inputLabelSx} value='yearly'>
                  {localization.body.assetModal.frequency.yearly}
                </Option>
                <Option sx={inputLabelSx} value='random'>
                  {localization.body.assetModal.frequency.random}
                </Option>
              </Select>
            </FormControl>
          </Grid>
          <Grid xs={4}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>{dayText}</FormLabel>
              <Input
                sx={inputLabelSx}
                type='number'
                name='split-day'
                disabled
                slotProps={{
                  input: {
                    min: 1,
                    max: splitDayMaxValue,
                  },
                }}
              />
            </FormControl>
          </Grid>
          <Grid xs={4}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>
                {localization.body.assetModal.numberOfPurchases}
              </FormLabel>
              <Input
                sx={inputLabelSx}
                type='number'
                name='split'
                disabled
                slotProps={{
                  input: {
                    min: 1,
                    max: 12,
                  },
                }}
              />
            </FormControl>
          </Grid>
          <Grid xs={4}>
            <Box display='flex' justifyContent='flex-end'>
              <Button variant='soft' color='primary' type='submit' disabled>
                {localization.body.assetModal.generatePurchases}
              </Button>
            </Box>
          </Grid>
        </Grid>

        <Divider role='presentation'>
          <Typography sx={dividerTextSx} mb={2} mt={2}>
            {localization.body.assetModal.onePurchase}
          </Typography>
        </Divider>
      </form>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const qtdElement = e.currentTarget.elements.namedItem(
            "qtd"
          ) as HTMLInputElement;
          const dateElement = e.currentTarget.elements.namedItem(
            "date"
          ) as HTMLInputElement;

          const partialPosition = {
            type: "qtd",
            qtd: qtdElement.value,
            date: dateElement.value,
          };
          addPosition(partialPosition);
        }}
      >
        <Grid
          container
          spacing={1}
          direction='row'
          justifyContent='space-between'
          alignItems='flex-end'
        >
          <Grid xs={5} md={4}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>
                {localization.body.assetModal.value}
              </FormLabel>
              <Input
                sx={inputLabelSx}
                type='number'
                name='qtd'
                error={qtdError}
                startDecorator='R$'
                //defaultValue={0.0}

                // startDecorator={{ real: 'R$', qtd: '' }[type]}
                // endDecorator={
                //   <Fragment>
                //     <Divider orientation="vertical" />
                //     <Select
                //       variant="plain"
                //       value={type}
                //       onChange={(_, value) => {
                //         setType(value!);
                //         updatePosition("type", value);
                //       }}
                //       sx={{ mr: -1.5, '&:hover': { bgcolor: 'transparent' } }}
                //     >
                //       <Option value="real">Valor</Option>
                //       {/* <Option value="qtd">Qtd.</Option> */}
                //     </Select>
                //   </Fragment>
                // }
                slotProps={{
                  input: {
                    min: 0,
                  },
                }}
              />
            </FormControl>
          </Grid>
          <Grid xs={7} md={5}>
            <FormControl>
              <FormLabel sx={inputLabelSx}>
                {localization.body.assetModal.date}
              </FormLabel>
              <Input
                sx={inputLabelSx}
                type='date'
                name='date'
                required
                slotProps={{
                  input: {
                    min: selectedAsset.minDate,
                    max: selectedAsset.maxDate,
                  },
                }}
              />
            </FormControl>
          </Grid>
          <Grid xs={12} md={3}>
            <Box display='flex' justifyContent='flex-end'>
              <Button
                variant='soft'
                color='primary'
                //loading={loading}
                type='submit'
              >
                {localization.body.assetModal.add}
              </Button>
            </Box>
          </Grid>
        </Grid>
      </form>
    </>
  );
}
