"use client";

import Stack from "@mui/material/Stack";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import Grid from "@mui/material/Grid";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useTranslation } from "react-i18next";
import { Controller, useFieldArray, useFormContext } from "react-hook-form";
import Link from "next/link";
import React from "react";
import MailField from "../MailField/MailField";
import { MailSetting } from "@/app/api/mail";
import { MailSave } from "@/app/api/mail/actions";
import { Checkbox, IconButton, InputAdornment } from "@mui/material";
import { Visibility, VisibilityOff } from "@mui/icons-material";

interface Props {
  isActive: boolean;
}

const SettingDetails: React.FC<Props> = ({ isActive }) => {
  const requiredFields = ["host", "port", "username"];
  const { t } = useTranslation();
  const {
    register,
    formState: { errors },
    control,
    watch,
  } = useFormContext<MailSave>();

  const { fields } = useFieldArray({
    control,
    name: "settings",
  });

  const [showSMTPPassword, setShowSMTPPassword] = React.useState(false);

  const handleClickShowPassword = () => setShowSMTPPassword((show) => !show);

  const handleMouseDownPassword = (
    event: React.MouseEvent<HTMLButtonElement>,
  ) => {
    event.preventDefault();
  };

  return (
    <Card sx={{ display: isActive ? "block" : "none" }}>
      <CardContent component={Stack} spacing={4}>
        <Box>
          <Typography variant="overline" display="block" marginBlockEnd={1}>
            {t("Settings")}
          </Typography>
          {fields.map((field, index) => (
            <Grid
              container
              key={"row-" + index}
              justifyContent="flex-start"
              alignItems="center"
              spacing={2}
              columns={{ xs: 6, sm: 12 }}
              sx={{ mt: 1 }}
            >
              <Grid item key={"col-1-" + index} xs={4}>
                <Typography variant="body2">{`${t(field.name)}${
                  requiredFields.some((name) =>
                    field.name.toLowerCase().includes(name),
                  )
                    ? "*"
                    : ""
                }`}</Typography>
              </Grid>
              {field.name.toLowerCase().includes("password") === true ? (
                <Grid item key={"col-2-" + index} xs={8}>
                  <TextField
                    label={t(field.name)}
                    type={showSMTPPassword ? "text" : "password"}
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            aria-label="toggle password visibility"
                            onClick={handleClickShowPassword}
                            onMouseDown={handleMouseDownPassword}
                          >
                            {showSMTPPassword ? (
                              <Visibility />
                            ) : (
                              <VisibilityOff />
                            )}
                          </IconButton>
                        </InputAdornment>
                      ),
                    }}
                    fullWidth
                    {...register(`settings.${index}.value`)}
                  />
                </Grid>
              ) : field.type.toLowerCase() === "boolean" ? (
                <Grid item xs={8}>
                  <Checkbox
                    {...register(`settings.${index}.value`)}
                    checked={Boolean(watch(`settings.${index}.value`))}
                  />
                </Grid>
              ) : field.type.toLowerCase() === "integer" ? (
                <Grid item xs={8}>
                  <TextField
                    label={t(field.name)}
                    type="number"
                    InputProps={{
                      inputProps: {
                        step: 1,
                        min: 0,
                      },
                    }}
                    fullWidth
                    {...register(`settings.${index}.value`, {
                      required: requiredFields.some((name) =>
                        field.name.toLowerCase().includes(name),
                      ),
                    })}
                    error={Boolean(
                      errors.settings &&
                        errors.settings.length &&
                        errors.settings.length > index &&
                        errors.settings[index]?.value,
                    )}
                  />
                </Grid>
              ) : (
                <Grid item xs={8}>
                  <TextField
                    label={t(field.name)}
                    fullWidth
                    {...register(`settings.${index}.value`, {
                      required: requiredFields.some((name) =>
                        field.name.toLowerCase().includes(name),
                      ),
                    })}
                    error={Boolean(
                      errors.settings &&
                        errors.settings.length &&
                        errors.settings.length > index &&
                        errors.settings[index]?.value,
                    )}
                  />
                </Grid>
              )}
            </Grid>
          ))}
        </Box>
      </CardContent>
    </Card>
  );
};

export default SettingDetails;
