"use client";
import React, { useState, useEffect } from "react";
import { Text, Button, TextInput, PasswordInput, Title, Card, Box, Image } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Providers } from "@/app/providers";
import { useRouter } from "next/navigation";
import NextImage from "next/image";
import logo from '@/app/image/logo.jpg';
import changePwdImage from '@/app/image/changepw.png';
// import CaptchaImage from './CaptchaImage';
import { IconEye, IconEyeOff, IconLock, IconLogout } from '@tabler/icons-react';

export default function ForgetLoginPwd() {
  const router = useRouter();
  const [authorized, SetAuthorized] = useState<boolean | null>(null);
  const [captcha, setCaptcha] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [captchaInput, setCaptchaInput] = useState('');
  const [captchaError, setCaptchaError] = useState('');
  const [confirmVisible, setConfirmVisible] = useState(false);
  const toggleConfirmVisibility = () => setConfirmVisible((v) => !v);
  const icon = <IconLock size={18} stroke={1.5} />;

  async function handleLogout(e: React.FormEvent) {
    e.preventDefault();
    localStorage.removeItem("access_token");
    router.push("/login")
  }

  useEffect(() => {
    generateCaptcha();
  }, []);

  const generateCaptcha = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 6; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptcha(result);
    setCaptchaInput('');
    setCaptchaError('');
  };

  async function handleSetLoginPassword(e: React.FormEvent) {
    e.preventDefault();
    const pwdRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
    if (!password || !confirmPassword) {
      notifications.show({
        withBorder: true,
        color: "red",
        title: "Both password fields are required.",
        message: "Both password fields are required.",
        autoClose: 5000,
      });
      return;
      // alert("Both password fields are required.");
    } else if (password !== confirmPassword) {
      // alert("Passwords do not match.");
      notifications.show({
        withBorder: true,
        color: "red",
        title: "Passwords do not match.",
        message: "Passwords do not match.",
        autoClose: 5000,
      });
      return;
    }
    else if (!pwdRegex.test(password)) {
      // alert("Password must contain at least 1 capital letter, 1 number, 1 special character, and be at least 8 characters long.");
      notifications.show({
        withBorder: true,
        color: "red",
        title: "Password must contain at least 1 capital letter, 1 number, 1 special character, and be at least 8 characters long.",
        message: "Password must contain at least 1 capital letter, 1 number, 1 special character, and be at least 8 characters long.",
        autoClose: 5000,
      });
      return;
    }
    else if (captchaInput !== captcha) {
      setCaptchaError("Incorrect CAPTCHA.");
      return;
    }
    const token = localStorage.getItem("access_token");
    const response = await fetch('api/auth/login_password', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        login_password: password,
      }),
    });
    const data = await response.json();
    if (response.ok) {
      console.log(data);
      notifications.show({
        withBorder: true,
        color: "green",
        title: "Login Password has been set",
        message: "Login Password has been set",
        autoClose: 5000,
      });
      router.push("/SetTxn");
    }
    else {
      notifications.show({
        withBorder: true,
        color: "red",
        title: "Please try again later ",
        message: "Please try again later ",
        autoClose: 5000,
      });
      router.push("/login");
    }
  }

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      SetAuthorized(false);
      router.push("/login");
    }
    else {
      SetAuthorized(true);
    }
  }, []);

  if (authorized) {
    return (
      <Providers>
        <div style={{ backgroundColor: "#f8f9fa", width: "100%", height: "auto", paddingTop: "5%" }}>
          <Box style={{
            position: 'fixed', width: '100%', height: '12%', top: 0, left: 0, zIndex: 100,
            display: "flex",
            justifyContent: "flex-start",
            background: "linear-gradient(15deg,rgba(2, 163, 85, 1) 55%, rgba(101, 101, 184, 1) 100%)"
          }}>
            <Image
              // radius="md"
              fit="cover"
              src={logo}
              component={NextImage}
              alt="ebanking"
              style={{ width: "100%", height: "100%" }}
            />
            <Button style={{
              position: 'absolute',
              top: '50%',
              left: '90%',
              color: 'white',
              textShadow: '1px 1px 2px black',
              fontSize: "20px"
            }}
              leftSection={<IconLogout color='white' />} variant="subtle" onClick={handleLogout}>Logout</Button>
          </Box>
          <div>
            <Box style={{ display: "flex", justifyContent: "center", alignItems: "center", columnGap: "5rem" }} bg="#c1e0f0">
              <Image h="85vh" fit="contain" component={NextImage} src={changePwdImage} alt="Change Password Image" />
              <Box h="100%" style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                <Card p="xl" w="40vw" h='82vh'>
                  <Title order={3}
                    // @ts-ignore
                    align="center" mb="md">Set Login Password</Title>

                  <form onSubmit={handleSetLoginPassword}>
                    <PasswordInput
                      label="Login Password"
                      placeholder="Enter your password"
                      required
                      id="loginPassword"
                      value={password}
                      onChange={(e) => setPassword(e.currentTarget.value)}
                      onCopy={(e) => e.preventDefault()}
                      onPaste={(e) => e.preventDefault()}
                      onCut={(e) => e.preventDefault()}
                    />

                    <PasswordInput
                      label="Confirm Login Password"
                      placeholder="Enter your password"
                      required
                      rightSection={icon}
                      id="confirmPassword"
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.currentTarget.value)}
                      type={confirmVisible ? 'text' : 'password'}
                      // rightSection={
                      //   <button
                      //     type="button"
                      //     onClick={toggleConfirmVisibility}
                      //     style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'grey' }}
                      //   >
                      //     {confirmVisible ? <IconEyeOff size={18} /> : <IconEye size={18} />}
                      //   </button>
                      // }
                      onCopy={(e) => e.preventDefault()}
                      onPaste={(e) => e.preventDefault()}
                      onCut={(e) => e.preventDefault()}

                    />

                    {/* CAPTCHA */}
                    <div style={{ marginTop: 20 }}>
                      <label style={{ fontWeight: 600 }}>Enter CAPTCHA *</label>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 5 }}>
                        {/* <CaptchaImage text={captcha} /> */}
                        <Button size="xs" variant="outline" onClick={generateCaptcha}>Refresh</Button>
                      </div>
                      <TextInput
                        placeholder="Enter above text"
                        value={captchaInput}
                        onChange={(e) => setCaptchaInput(e.currentTarget.value)}
                        required
                      />
                      {captchaError && <p style={{ color: 'red',fontSize:'12px' }}>{captchaError}</p>}
                    </div>

                    <Button
                      type="submit"
                      fullWidth
                      mt="sm"
                      color="blue"
                    >
                      Set
                    </Button>
                  </form>
                  <br></br>
                  <Box
                    style={{
                      flex: 1,
                      borderLeft: '1px solid #ccc',
                      paddingLeft: 16,
                      minHeight: 90,

                    }}
                  >
                    <Text size="sm">
                      <strong>Note:</strong> Password will contains minimum one alphabet, one digit, one special symbol and total 8 charecters.
                    </Text>
                  </Box>
                </Card>
              </Box>
            </Box>
            <Box
              style={{
                flexShrink: 0,
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                backgroundColor: "#f8f9fa",
                marginTop: "0.5rem",
              }}
            >
              <Text c="dimmed" size="xs">
                © 2025 Kangra Central Co-Operative Bank
              </Text>
            </Box>
          </div>
        </div>
      </Providers >
    );
  }
}