"use client";

import React, { useState, ChangeEvent, useEffect } from "react";
import "./AccountForm.css";
import { getUserInfo } from "@/app/utils/token";
import { validateDate, formatDateForInput } from "@/app/utils/datehelpers";
import Swal from "sweetalert2";
import { useDispatch } from "react-redux";
import Cookies from "js-cookie";
import {
  cancelUser,
  updateEmail,
  updateOrganizationContact,
  updateBasicUserInfo,
  updatePassword,
} from "@/app/redux/services/main/advert/homeServicess";
import { useSettingsData } from "@/app/hooks/useData";
type FormDataType = Record<string, string>;

export default function AccountFormSection() {
  const dispatch = useDispatch();
  const { data: translations } = useSettingsData();
  const t = translations || {};
  const [userInfo, setUserInfo] = useState<any>(null);
  const [isLoading, setIsLoading] = useState<string | null>(null);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [editMode, setEditMode] = useState({
    email: false,
    password: false,
  });
  const handleCancelEdit = (field: "email" | "password") => {
    setEditMode((prev) => ({
      ...prev,
      [field]: false,
    }));
    if (field === "password") {
      setFormData((prev) => ({ ...prev, password: "" }));
    }
    if (field === "email" && userInfo) {
      setFormData((prev) => ({ ...prev, email: userInfo.email || "" }));
    }
  };
  const handleEditClick = (field: "email" | "password") => {
    setEditMode((prev) => ({
      ...prev,
      [field]: true,
    }));
  };
  const [formData, setFormData] = useState<FormDataType>({
    sur_name: "",
    christian_name: "",
    date_of_birth: "",
    phone: "",
    organization: "",
    person_to_contact: "",
    community: "",
    email: "",
    password: "",
    photo: "",
  });
  useEffect(() => {
    const userData = getUserInfo();
    setUserInfo(userData);

    if (userData) {
      console.log(userData);
      setFormData({
        sur_name: userData.sur_name || "",
        christian_name: userData.christian_name || "",
        date_of_birth: formatDateForInput(userData.date_of_birth) || "",
        phone: userData.phone || "",
        organization: userData.organization || "",
        person_to_contact: userData.person_to_contact || "",
        community: userData.community || "",
        email: userData.email || "",
        password: "",
        photo: userData.email || "",
      });
    }
  }, []);

  const updateLocalUserInfo = (updatedFields: any) => {
    const currentUserInfo = getUserInfo();
    if (currentUserInfo) {
      const updatedUserInfo = {
        ...currentUserInfo,
        ...updatedFields,
      };
      // Update localStorage
      localStorage.setItem("user_info", JSON.stringify(updatedUserInfo));
      // Update cookies
      Cookies.set("user_info", JSON.stringify(updatedUserInfo));

      if (updatedFields.user_id !== undefined) {
        localStorage.setItem("user_id", JSON.stringify(updatedFields.user_id));
        Cookies.set("user_id", JSON.stringify(updatedFields.user_id));
      }
    }
  };
  const handleChange = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    if (name === "date_of_birth") {
      const dateError = validateDate(value);
      setErrors((prev) => ({ ...prev, date_of_birth: dateError }));
    }
  };

  // section must be a string

  const handleSubmit = async (section: string) => {
    setIsLoading(section);
    if (section === "Account Information") {
      const dateError = validateDate(formData.date_of_birth);
      if (dateError) {
        setErrors((prev) => ({ ...prev, date_of_birth: dateError }));
        return;
      }
    }

    try {
      let result;

      switch (section) {
        case "Account Information":
          result = await dispatch(
            updateBasicUserInfo({
              christian_name: formData.christian_name,
              sur_name: formData.sur_name,
              name: `${formData.christian_name} ${formData.sur_name}`,
              date_of_birth: formData.date_of_birth,
              phone: formData.phone,
            }) as any
          ).unwrap();
          updateLocalUserInfo({
            christian_name: formData.christian_name,
            sur_name: formData.sur_name,
            name: `${formData.christian_name} ${formData.sur_name}`,
            date_of_birth: formData.date_of_birth,
            phone: formData.phone,
          });
          break;

        case "Organisation":
          result = await dispatch(
            updateOrganizationContact({
              organization: formData.organization,
              person_to_contact: formData.person_to_contact,
            }) as any
          ).unwrap();
          updateLocalUserInfo({
            organization: formData.organization,
            person_to_contact: formData.person_to_contact,
          });
          break;

        case "Email":
          result = await dispatch(updateEmail(formData.email) as any).unwrap();
          updateLocalUserInfo({
            email: formData.email,
          });
          break;

        case "Password":
          if (!formData.password) {
            Swal.fire({
              icon: "warning",
              title:
                t.messages?.error?.passwordRequired?.title ||
                "Password Required",
              text:
                t.messages?.error?.passwordRequired?.text ||
                "Please enter a new password",
              confirmButtonText: "OK",
            });
            setIsLoading(null);
            return;
          }
          result = await dispatch(
            updatePassword({
              currentPassword: "", // You might need to add current password field
              newPassword: formData.password,
            }) as any
          ).unwrap();
          break;
        case "CancelAccount":
          result = await Swal.fire({
            title: t.cancelAccount?.confirmationTitle || "Êtes-vous sûr ?",
            text:
              t.cancelAccount?.confirmationText ||
              "Cette action est irréversible et entraînera la perte définitive de toutes vos données.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d33",
            cancelButtonColor: "#3085d6",
            confirmButtonText:
              t.cancelAccount?.confirmButton || "SUPPRIMER MON COMPTE",
            cancelButtonText:
              t.cancelAccount?.cancelButton || "CONSERVER MON COMPTE",
          });
          if (result.isConfirmed) {
            setIsLoading("Cancel Account");
            try {
              await dispatch(cancelUser() as any).unwrap();

              Swal.fire({
                title: t.cancelAccount?.successTitle || "Account Cancelled!",
                text:
                  t.cancelAccount?.successText ||
                  "Your account has been successfully cancelled.",
                icon: "success",
                confirmButtonText: "OK",
              }).then(() => {
                localStorage.removeItem("user_info");
                localStorage.removeItem("user_id");
                Cookies.remove("token");
                window.location.href = "/login";
              });
            } catch (error: any) {
              const errorMessage = error?.message || "Failed to cancel account";
              Swal.fire({
                title: t.cancelAccount?.errorTitle || "Cancellation Failed",
                text: errorMessage,
                icon: "error",
                confirmButtonText: "OK",
              });
            } finally {
              setIsLoading(null);
            }
          }
        default:
          console.log(`Unknown section: ${section}`);
          setIsLoading(null);
          return;
      }

      Swal.fire({
        icon: "success",
        title: t.messages?.success?.title || "Terminé",
        text:
          result.message ||
          `${section} ${t.messages?.success?.text || "updated successfully!"}`,
        confirmButtonText: "OK",
      });

      // Clear password field after successful update
      if (section === "Password") {
        setFormData((prev) => ({ ...prev, password: "" }));
      }
    } catch (error: any) {
      const errorMessage = error?.message || `Failed to update ${section}`;

      Swal.fire({
        icon: "error",
        title: t.messages?.error?.title || "Mise à jour impossible",
        text: errorMessage,
        confirmButtonText: "OK",
      });
    } finally {
      setIsLoading(null);
    }
  };

  const handleCancel = () => {
    if (confirm("Are you sure you want to cancel your account?")) {
      console.log("Account cancelled");
    }
  };

  return (
    <div className="account-container">
      <form className="form-wrapper">
        {/* Account Information Section */}
        <section className="form-section">
          <div className="section-title">
            <div className="section-title-child">
              {t.accountInformation?.sectionTitle || "Account Information"}
            </div>
            <div className="parent-content-container">
              <div className="sectiontittle-satric">*</div>
              <div className="required-indicator">
                {" "}
                {t.accountInformation?.required || "required"}
              </div>
            </div>
          </div>

          <div className="form-row">
            <div className="form-group">
              <label htmlFor="surname">
                {t.accountInformation?.surname || "Surname"}{" "}
                <p className="sectiontittle-satric">*</p>
              </label>
              <input
                type="text"
                id="surname"
                name="sur_name"
                value={formData.sur_name}
                onChange={handleChange}
                className="form-input"
              />
            </div>

            <div className="form-group">
              <label htmlFor="christianName">
                {t.accountInformation?.christianName || "Christian Name"}{" "}
                <span className="required">*</span>
              </label>
              <input
                type="text"
                id="christianName"
                name="christian_name"
                value={formData.christian_name}
                onChange={handleChange}
                className="form-input"
              />
            </div>

            <div className="form-group">
              <label htmlFor="birthdate">
                {t.accountInformation?.birthdate || "Birthdate"}{" "}
                <span className="required">*</span>
              </label>
              <input
                type="date"
                id="birthdate"
                name="date_of_birth"
                value={formData.date_of_birth}
                onChange={handleChange}
                className={`form-input ${errors.date_of_birth ? "error" : ""}`}
              />
              {errors.date_of_birth && (
                <div className="error-message">{errors.date_of_birth}</div>
              )}
            </div>
          </div>

          <div className="form-row">
            <div className="form-group full-width">
              <label htmlFor="mobileNumber">
                {t.accountInformation?.mobileNumber || "Mobile Number"}
              </label>
              <input
                type="text"
                id="mobileNumber"
                name="phone"
                value={formData.phone}
                onChange={handleChange}
                className="form-input"
              />
            </div>
          </div>

          <button
            type="button"
            onClick={() => handleSubmit("Account Information")}
            className="save-btn"
          >
            {isLoading === "Account Information"
              ? t.accountInformation?.saving || "Saving..."
              : t.accountInformation?.saveButton || "Save your modifications"}
          </button>
        </section>

        <div className="section-divider"></div>

        {/* Organisation Name Section */}
        <section className="form-section">
          <h2 className="section-titleTwo">
            {t.organisation?.sectionTitle || "Organisation Name"}
          </h2>

          <div className="form-row">
            <div className="form-grouptwo full-width">
              <label htmlFor="organisation">
                {t.organisation?.associationLabel ||
                  "Association, Club or Organism"}
              </label>
              <input
                type="text"
                id="organisation"
                name="organization"
                value={formData.organization}
                onChange={handleChange}
                className="form-inputtwo"
              />
            </div>
          </div>

          <div className="form-row">
            <div className="form-group-three full-width">
              <label htmlFor="personToContact">
                {t.organisation?.personToContact || "Person to Contact"}
              </label>
              <input
                type="text"
                id="personToContact"
                name="person_to_contact"
                value={formData.person_to_contact}
                onChange={handleChange}
                className="form-input"
              />
            </div>
          </div>

          <button
            type="button"
            onClick={() => handleSubmit("Organisation")}
            className="save-btn"
          >
            {isLoading === "Organisation"
              ? t.organisation?.saving || "Saving..."
              : t.organisation?.saveButton || "Save your modifications"}
          </button>
        </section>

        <div className="section-divider"></div>

        {/* Email Address Section */}
        <section className="form-section">
          <h2 className="section-title-three">
            {t.email?.sectionTitle || "Email Address"}
          </h2>

          <div className="form-row">
            <div className="form-group-Fourth full-width email-group input-with-edit">
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                className="form-input edit-input"
                disabled={!editMode.email}
              />
              {editMode.email ? (
                <span
                  className="edit-text cancel-text"
                  onClick={() => handleCancelEdit("email")}
                >
                  {t.email?.cancel || "cancel"}
                </span>
              ) : (
                <span
                  className="edit-text"
                  onClick={() => handleEditClick("email")}
                >
                  {t.email?.edit || "edit"}
                </span>
              )}
            </div>
          </div>

          <button
            type="button"
            onClick={() => handleSubmit("Email")}
            disabled={!editMode.email || isLoading === "Email"}
            className="save-btn"
          >
            {isLoading === "Email"
              ? t.email?.saving || "Saving..."
              : t.email?.saveButton || "Save your modifications"}
          </button>
        </section>

        <div className="section-divider"></div>

        {/* Password Change Section */}
        <section className="form-section">
          <h2 className="section-title-three">
            {t.password?.sectionTitle || "Password change"}
          </h2>

          <div className="form-row">
            <div className="form-group-Fourth full-width email-group input-with-edit">
              {/* <input
                type="password"
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                className="form-input edit-input"
               /> */}
              <input
                type="password"
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                className="form-input edit-input"
                placeholder={t.password?.placeholder || "************"}
                disabled={!editMode.password}
              />{" "}
              {editMode.password ? (
                <span
                  className="edit-text cancel-text"
                  onClick={() => handleCancelEdit("password")}
                >
                  {t.password?.cancel || "cancel"}
                </span>
              ) : (
                <span
                  className="edit-text"
                  onClick={() => handleEditClick("password")}
                >
                  {t.password?.edit || "edit"}
                </span>
              )}
            </div>
          </div>

          <button
            type="button"
            onClick={() => handleSubmit("Password")}
            disabled={!editMode.password || isLoading === "Password"}
            className="save-btn"
          >
            {isLoading === "Password"
              ? t.password?.saving || "Saving..."
              : t.password?.saveButton || "Save your modifications"}
          </button>
        </section>

        <div className="section-divider"></div>

        {/* Cancel Account */}
        <div className="cancel-section">
          <button
            type="button"
            onClick={() => handleSubmit("CancelAccount")}
            className="cancel-btn"
          >
            {t.cancelAccount?.buttonText || "Cancel your Account"}
          </button>
          <div className="paraagraph-cancelsection">
            {t.cancelAccount?.description ? (
              t.cancelAccount.description
                .split("\n")
                .map((line: string, index: number, arr: string[]) => (
                  <React.Fragment key={index}>
                    {line}
                    {index < arr.length - 1 && <br />}
                  </React.Fragment>
                ))
            ) : (
              <>
                La suppression de votre compte supprime toutes les <br />
                informations de notre base de données.
                <br />
                Ces informations ne peuvent pas être récupérées.
              </>
            )}
          </div>
        </div>
        <div className="section-divider"></div>
      </form>
    </div>
  );
}
