"use client";
import LtrTextField from "@/core/components/LtrTextField";
import StyledForm from "@/core/components/StyledForm";
import { GET_USER_LOGIN_ROUTE } from "@/core/utils/routes";
import { useAuth } from "@/lib/contexts/auth";
import useRequest from "@/lib/hooks/useRequest";
import { yupResolver } from "@hookform/resolvers/yup";
import {
  Lock,
  Person,
  PhoneCallback,
  Visibility,
  VisibilityOff,
} from "@mui/icons-material";
import {
  Button,
  Container,
  IconButton,
  InputAdornment,
  Stack,
  Typography,
} from "@mui/material";
import { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { object, string } from "yup";

const LoginForm = () => {
  const [showPassword, setShowPassword] = useState(false);
  const requestServer = useRequest();
  const { getUser } = useAuth();
  const defaultValues = {
    username: "",
    password: "",
    telephone_id: "",
  };

  const validationSchema = object({
    username: string().required("لطفا نام کاربری را وارد کنید!"),
    password: string().required("لطفا رمز عبور را وارد کنید!"),
    telephone_id: string().required("لطفا شماره تماس داخلی را وارد کنید!"),
  });

  const {
    control,
    handleSubmit,
    formState: { isSubmitting },
  } = useForm({
    defaultValues,
    resolver: yupResolver(validationSchema),
    mode: "all",
  });

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

  const onSubmit = async (data) => {
    try {
      const formData = new FormData();
      formData.append("username", data.username);
      formData.append("password", data.password);
      formData.append("telephone_id", data.telephone_id);
      await requestServer(GET_USER_LOGIN_ROUTE, "post", {
        data: formData,
      });
      getUser();
    } catch (error) {}
  };

  return (
    <Container maxWidth="xs" sx={{ flex: 1 }}>
      <StyledForm
        onSubmit={handleSubmit(onSubmit)}
        style={{ width: "100%", height: "100%" }}
      >
        <Stack
          sx={{ width: "100%", height: "100%" }}
          justifyContent="center"
          alignItems="center"
          spacing={6}
        >
          <Stack
            sx={{ width: "100%", mb: 2 }}
            justifyContent="center"
            alignItems="center"
          >
            <Typography
              variant="h4"
              color="primary"
              fontWeight={600}
              textAlign="center"
            >
              ورود به سامانه CRM
            </Typography>
          </Stack>
          <Stack sx={{ width: "100%", p: 2 }} spacing={4}>
            <Stack spacing={2}>
              <Controller
                control={control}
                render={({ field, fieldState: { error } }) => {
                  return (
                    <LtrTextField
                      {...field}
                      label="نام کاربری"
                      variant="outlined"
                      slotProps={{
                        input: {
                          endAdornment: (
                            <InputAdornment position="end">
                              <Person />
                            </InputAdornment>
                          ),
                        },
                      }}
                      fullWidth
                      error={!!error}
                      helperText={!!error && error.message}
                    />
                  );
                }}
                name={"username"}
              />
              <Controller
                control={control}
                render={({ field, fieldState: { error } }) => {
                  return (
                    <LtrTextField
                      {...field}
                      label="رمزعبور"
                      variant="outlined"
                      type={showPassword ? "text" : "password"}
                      slotProps={{
                        input: {
                          startAdornment: (
                            <InputAdornment position="start">
                              <IconButton onClick={handleClickShowPassword}>
                                {showPassword ? (
                                  <VisibilityOff />
                                ) : (
                                  <Visibility />
                                )}
                              </IconButton>
                            </InputAdornment>
                          ),
                          endAdornment: (
                            <InputAdornment position="end">
                              <Lock />
                            </InputAdornment>
                          ),
                        },
                      }}
                      fullWidth
                      error={!!error}
                      helperText={!!error && error.message}
                    />
                  );
                }}
                name={"password"}
              />
              <Controller
                control={control}
                render={({ field, fieldState: { error } }) => {
                  return (
                    <LtrTextField
                      {...field}
                      label="شماره تماس داخلی"
                      variant="outlined"
                      type="tel"
                      slotProps={{
                        input: {
                          endAdornment: (
                            <InputAdornment position="end">
                              <PhoneCallback />
                            </InputAdornment>
                          ),
                        },
                      }}
                      fullWidth
                      error={!!error}
                      helperText={!!error && error.message}
                    />
                  );
                }}
                name={"telephone_id"}
              />
            </Stack>
            <Stack>
              <Button
                variant="contained"
                color="primary"
                size="large"
                type={"submit"}
                disabled={isSubmitting}
              >
                {isSubmitting ? "درحال ورود..." : "ورود"}
              </Button>
            </Stack>
          </Stack>
        </Stack>
      </StyledForm>
    </Container>
  );
};
export default LoginForm;
