import React, { useCallback, useMemo, useState } from "react";
import { FaEyeSlash, FaEye } from "react-icons/fa";
import { TaleDashbaordMainCard } from "@components/TaleDashbaordMainCard";
import { TaleInput } from "@components/TaleInput";
import { TaleCheckbox } from "@components/TaleCheckbox";
import TaleButton from "@components/TaleButton";
import { authService } from "@/services/auth";

const ChangePasswordConnected = () => {
    const [state, setstate] = useState({
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
        visibleOld: false,
        visibleNew: false,
        visibleConfirm: false,
        loading: false,
        error: null,
        success: false,
    });

    const specs = useMemo(
        () => [
            {
                label: "At least 8 characters",
                checked: state.newPassword.length >= 8,
            },
            {
                label: "Contains a symbol or a number",
                checked: /[\d\W]/.test(state.newPassword),
            },
        ],
        [state.newPassword]
    );

    const isWeak = !specs.every((s) => s.checked);
    const mismatch =
        state.confirmPassword.length > 0 && state.newPassword !== state.confirmPassword;
    const canSubmit =
        state.oldPassword.length > 0 &&
        !isWeak &&
        !mismatch &&
        state.confirmPassword.length > 0 &&
        !state.loading;

    const eyeIcon = (visible, key) => (
        <div
            className="cursor-pointer"
            onClick={() => setstate((prv) => ({ ...prv, [key]: !prv[key] }))}
        >
            {visible ? <FaEyeSlash /> : <FaEye />}
        </div>
    );

    const handleSubmit = useCallback(async () => {
        if (!canSubmit) return;
        setstate((prv) => ({ ...prv, loading: true, error: null, success: false }));

        const result = await authService.changeAccountPassword(
            state.oldPassword,
            state.newPassword
        );

        if (result.success) {
            setstate((prv) => ({ ...prv, loading: false, success: true }));
            setTimeout(() => {
                authService.logout();
            }, 1000);
        } else {
            setstate((prv) => ({
                ...prv,
                loading: false,
                error:
                    result.error ||
                    "Failed to change password. Please check your current password and try again.",
            }));
        }
    }, [canSubmit, state.oldPassword, state.newPassword]);
    return (
        <div className="flex flex-col gap-4">
            {/* Decorative header banner, matching Account Area */}
            <div
                className="rounded-2xl p-8 flex flex-col justify-center"
                style={{
                    background: "linear-gradient(94deg, #B0EEFF 0%, #FFD0EC 100%)",
                    minHeight: "140px",
                }}
            >
                <h1 className="!text-3xl font-bold !m-0 text-[#111111]">Security</h1>
                <p className="text-[#333333] mt-1">
                    Update your password to keep your account secure.
                </p>
            </div>

            <TaleDashbaordMainCard className="flex flex-col gap-6 !max-w-2xl">
                <div className="flex flex-col gap-1">
                    <h2 className="!text-xl md:!text-2xl font-bold !m-0">Change password</h2>
                </div>

                <div className="flex flex-col gap-6">
                    <TaleInput
                        value={state.oldPassword}
                        onChange={(e) =>
                            setstate((prv) => ({ ...prv, oldPassword: e.target.value }))
                        }
                        label="Current password"
                        inputClassName="!bg-white"
                        className="w-full"
                        type={state.visibleOld ? "text" : "password"}
                        suffix={eyeIcon(state.visibleOld, "visibleOld")}
                    />

                    <TaleInput
                        value={state.newPassword}
                        onChange={(e) =>
                            setstate((prv) => ({ ...prv, newPassword: e.target.value }))
                        }
                        label="New password"
                        inputClassName="!bg-white"
                        className="w-full"
                        type={state.visibleNew ? "text" : "password"}
                        suffix={eyeIcon(state.visibleNew, "visibleNew")}
                    />

                    {state.newPassword.length > 0 && (
                        <section className="flex flex-col gap-2 justify-start items-start w-full">
                            <p className="text-[#666]">Password strength:</p>
                            <div className="flex flex-col gap-3">
                                {specs.map((e, i) => (
                                    <TaleCheckbox
                                        key={i}
                                        label={<span className="text-[#B3B3B3]">{e.label}</span>}
                                        containerClassName="!cursor-default"
                                        className="!rounded-full"
                                        width={24}
                                        height={24}
                                        checked={e.checked}
                                    />
                                ))}
                            </div>
                        </section>
                    )}

                    <TaleInput
                        value={state.confirmPassword}
                        onChange={(e) =>
                            setstate((prv) => ({ ...prv, confirmPassword: e.target.value }))
                        }
                        label="Confirm new password"
                        inputClassName="!bg-white"
                        className="w-full"
                        type={state.visibleConfirm ? "text" : "password"}
                        suffix={eyeIcon(state.visibleConfirm, "visibleConfirm")}
                    />

                    {mismatch && (
                        <p className="text-sm text-red-600 -mt-3">Passwords do not match.</p>
                    )}
                    {state.error && <p className="text-sm text-red-600">{state.error}</p>}
                    {state.success && (
                        <p className="text-sm text-green-600">
                            Your password has been changed successfully.
                        </p>
                    )}

                    <TaleButton
                        role="normal"
                        loading={state.loading}
                        disabled={!canSubmit}
                        onClick={handleSubmit}
                        className="!h-[51px] !rounded-xl !self-start !px-8"
                    >
                        Update password
                    </TaleButton>
                </div>
            </TaleDashbaordMainCard>
        </div>
    );
};

export default ChangePasswordConnected;