"use client";
import React, { useState, useEffect } from "react";
import { Text, Button, TextInput, PasswordInput, Title, Card, Group, Flex, Box, Image, Anchor, Stack, Container, rem, Grid } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { Providers } from "@/app/providers";
import { useRouter } from "next/navigation";
import NextImage from "next/image";
import myImage from '@/app/image/ebanking.jpg';
import changePwdImage from '@/app/image/changepw.png';
import dynamic from 'next/dynamic';
import RegistrationTimeline from '../_components/timeline/RegistrationTimeline';
import CaptchaImage from './CaptchaImage'; // adjust path if needed





function generateCaptcha(length = 6) {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join("");
}

export default function Login() {
  const router = useRouter();
  // const [error, setError] = useState<string | null>(null);
  //const [CIF, SetCIF] = useState("");
  // const [psw, SetPsw] = useState("");
  const [captcha, setCaptcha] = useState("");
  const [inputCaptcha, setInputCaptcha] = useState("");

  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");

  const ClientCarousel = dynamic(() => import('./clientCarousel'), { ssr: false });

  // const [captcha, setCaptcha] = useState('');
  const [captchaInput, setCaptchaInput] = useState('');
  const [captchaError, setCaptchaError] = useState('');




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

  // const regenerateCaptcha = () => {
  //   setCaptcha(generateCaptcha());
  //   setInputCaptcha("");
  // };

  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('');
  };

  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 }}>
          <Image
            // radius="md"
            fit="cover"
            src={myImage}
            component={NextImage}
            alt="ebanking"
            style={{ width: "100%", height: "100%" }}
          />
        </Box>
        <div style={{ marginTop: '10px' }}>

          <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="35vw">
                <Title order={3}
                  // @ts-ignore
                  align="center" mb="md">Change User Login Password</Title>

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

                  <PasswordInput
                    label="Confirm Login Password"
                    placeholder="Enter your password"
                    required
                    id="confirmPassword"
                    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' }}>{captchaError}</p>}
                  </div>




                  {/* <Button fullWidth mt="sm" color="blue" onClick={() => {
                    router.push("/ChangeTxn")
                  }} >
                    Set
                  </Button> */}

                  <Button
                    fullWidth
                    mt="sm"
                    color="blue"
                    onClick={() => {
                      let pwd = (document.getElementById("loginPassword") as HTMLInputElement).value;
                      let confirmPwd = (document.getElementById("confirmPassword") as HTMLInputElement).value;
                      const pwdRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
                      if (!pwd || !confirmPwd) {
                        alert("Both password fields are required.");
                      } else if (pwd !== confirmPwd) {
                        alert("Passwords do not match.");
                      }
                      else if (!pwdRegex.test(pwd)) {
                        alert("Password must contain at least 1 capital letter, 1 number, 1 special character, and be at least 8 characters long.");
                      }
                      else if (captchaInput !== captcha) {
                        setCaptchaError("Incorrect CAPTCHA.");
                      }

                      else {
                        // If all checks pass
                        router.push("/ChangeTxn");
                        notifications.show({
                          title: 'Password Change',
                          message: 'Login Password has been sucessfully updated',
                          color: "green",
                          position: 'bottom-center',
                        })
                      }
                    }}
                  >
                    Set
                  </Button>
                  {/* <Button onClick={() => {
                    notifications.show({
                      title: 'Default notification',
                      message: 'Do not forget to star Mantine on GitHub! test',
                    })
                  }} >Test</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
            component="footer"
            style={{
              width: "100%",
              textAlign: "center",
              padding: "10px 0",
              bottom: 0,
              left: 0,
              zIndex: 1000,
              fontSize: "14px",
            }}
          >
            <Text>
              © 2025 KCC Bank. All rights reserved. {" "}

            </Text>
          </Box>
        </div>
      </div>
    </Providers >
  );
}
