"use client";
import React from "react";

import { useState, useEffect } from "react";
import { fetchWrapper } from "@/helpers";
import { userService } from "@/services";

import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import Swal from "sweetalert2";

import { checkIsNotLogged } from "@/utlis/authCheck";

import { Trash2, CheckCheck } from "lucide-react";

import { useT } from "@/context/I18nContext"; 

export default function AccountEdit() {
	checkIsNotLogged("/");

     const { t } = useT(); 

	const fetchUserData = async () => {
		try {
			const data = await fetchWrapper.get("/api/users/getdata");

			const userData = data[0]?.userData;
			if (userData) {
				document.getElementById("firstName").value = userData.firstName || "";
				document.getElementById("lastName").value = userData.lastName || "";
				document.getElementById("email").value = userData.email || "";
			}
		} catch (error) {
			console.error("Error fetching user data:", error);
		}
	};

	useEffect(() => {
		fetchUserData();
	});

	const handleSubmit = async (e) => {
		e.preventDefault();

		const firstName = document.getElementById("firstName").value;
		const lastName = document.getElementById("lastName").value;
		const email = document.getElementById("email").value;
		const currentPassword = document.getElementById("currentPassword").value;
		const newPassword = document.getElementById("newPassword").value;
		const passwordConfirm = document.getElementById("passwordConfirm").value;

		const response = await fetchWrapper.post("/api/users/updatedata", {
			firstName,
			lastName,
			email,
			currentPassword,
			newPassword,
			passwordConfirm,
		});

		if (response.success) {
			toast.success("Datele au fost actualizate cu success.");
		} else {
			toast.error(response.error || "Eroare la actualizarea datelor.");
		}
	};

	const handleDeleteAccount = async (e) => {
		e.preventDefault();

		const result = await Swal.fire({
			title: "Ștergere cont",
			html: `
            <p style="color: #555; font-size: 15px; line-height: 1.7; margin: 0">
                Ești pe cale să îți ștergi permanent contul.<br/><br/>
                <strong>Toate datele asociate</strong> — comenzi, adrese, informații personale — 
                vor fi eliminate complet din sistemul nostru și 
                <strong>nu vor putea fi recuperate</strong>.<br/><br/>
                Dacă ești sigur că dorești să continui, confirmă acțiunea mai jos.
            </p>
        `,
			icon: "warning",
			iconColor: "#e53e3e",
			showCancelButton: true,
			confirmButtonText: "Da, șterge contul",
			cancelButtonText: "Anulează",
			confirmButtonColor: "#e53e3e",
			cancelButtonColor: "#718096",
			reverseButtons: true,
			focusCancel: true, // focusul implicit pe Anulează, mai sigur
			customClass: {
				title: "swal-title",
				popup: "swal-popup",
			},
		});

		if (result.isConfirmed) {
			try {
				const response = await fetchWrapper.delete("/api/users/deleteaccount");
				if (response.message === 'Contul a fost șters cu succes.') {
					await Swal.fire({
						title: "Cont șters",
						text: "Contul tău a fost șters cu succes. Ne pare rău să te vedem plecând.",
						icon: "success",
						confirmButtonColor: "#48bb78",
						confirmButtonText: "Închide",
					});
                         await userService.logout();
					window.location.href = "/";
				} else {
					toast.error(response.error || "Eroare la ștergerea contului.");
				}
			} catch (error) {
				toast.error("A apărut o eroare. Încearcă din nou.");
			}
		}
	};

	return (
		<div className='my-account-content account-edit'>
			<div className=''>
				<form onSubmit={handleSubmit} className='' id='form-password-change'>
					<div className='tf-field style-1 mb_15'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='text'
							id='firstName'
							required
							name='first name'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property1'>
							{t("checkout_prenume")}
						</label>
					</div>
					<div className='tf-field style-1 mb_15'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='text'
							required
							id='lastName'
							name='last name'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property2'>
							{t("checkout_nume_de_familie")}
						</label>
					</div>
					<div className='tf-field style-1 mb_15'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='email'
							autoComplete='abc@xyz.com'
							required
							id='email'
							name='email'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property3'>
							Email
						</label>
					</div>
					<h6 className='mb_20'>{t("contul_meu_pass_heading")}</h6>
					<div className='tf-field style-1 mb_30'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='password'
							required
							autoComplete='current-password'
							id='currentPassword'
							name='password'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property4'>
							{t("contul_meu_parola_curenta")}
						</label>
					</div>
					<div className='tf-field style-1 mb_30'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='password'
							id='newPassword'
							autoComplete='current-password'
							name='password'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property5'>
							{t("contul_meu_parola_noua")}
						</label>
					</div>
					<div className='tf-field style-1 mb_30'>
						<input
							className='tf-field-input tf-input'
							placeholder=' '
							type='password'
							id='passwordConfirm'
							autoComplete='current-password'
							name='password'
						/>
						<label className='tf-field-label fw-4 text_black-2' htmlFor='property6'>
							{t("contul_meu_parola_noua_confirm")}
						</label>
					</div>
					<div className='mb_20'>
						<button
							type='submit'
							className='tf-btn w-100 radius-3 btn-fill animate-hover-btn justify-content-center'>
							<CheckCheck size={18} /> {t("contul_meu_save")}
						</button>

						<button
							type='button'
							onClick={handleDeleteAccount}
							className='btn-danger tf-btn w-100 radius-3 btn-fill animate-hover-btn justify-content-center'
							style={{ marginTop: 10 }}>
							<Trash2 size={18} /> {t("contul_meu_delete")}
						</button>
					</div>
				</form>
			</div>
		</div>
	);
}
