import { assetPath } from "../../utils/assetPath";

import React, { useEffect, useRef, useState } from "react";
import Layout from "../../Layout";
import { useProfile } from "../../context/ProfileContext";
import {
  changePassword,
  updateProfile,
  uploadProfileImage,
} from "../../services/profileService";
import CustomSelect from "../../components/common/CustomSelect";
import { toast } from "react-toastify";
import Link from "next/link";

export default function ProfileSetting() {
  const { profile, refreshProfile } = useProfile();
  const [form, setForm] = useState({
    full_name: "",
    phone_number: "",
    email: "",
    organization_name: "",
    address: "",
    status: "",
  });
  const [passwordForm, setPasswordForm] = useState({
    current_password: "",
    new_password: "",
    confirm_password: "",
  });
  const [showPassword, setShowPassword] = useState({
    current_password: false,
    new_password: false,
    confirm_password: false,
  });
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef(null);
  const [errors, setErrors] = useState({});

  useEffect(() => {
    if (profile) {
      setForm({
        full_name: profile?.details?.full_name || "",
        phone_number: profile?.details?.phone_number || "",
        email: profile?.email || "",
        organization_name: profile?.details?.organization_name || "",
        address: profile?.details?.address || "",
        status: profile?.details?.status || "",
      });
    }
  }, [profile]);

  const handleChange = (e) => {
    const { name, value } = e.target;

    let formattedValue = value;

    if (name === "phone_number") {
      formattedValue = formatUSPhone(value);
    }

    if (name === "full_name") {
      formattedValue = value.replace(/[^A-Za-z\s]/g, "");
    }

    setForm((prev) => ({
      ...prev,
      [name]: formattedValue,
    }));

    setErrors((prev) => ({
      ...prev,
      [name]: validateField(name, formattedValue),
    }));
  };

  const handleSave = async () => {
    const validationErrors = {
      full_name: validateField("full_name", form.full_name),
      email: validateField("email", form.email),
      phone_number: validateField("phone_number", form.phone_number),
    };

    setErrors(validationErrors);

    if (Object.values(validationErrors).some(Boolean)) {
      return;
    }
    if (!form.full_name) {
      toast.error("Full Name is required!");
      return;
    }

    if (!form.status) {
      toast.error("Please select a status!");
      return;
    }
    try {
      const payload = {
        username: profile.username,
        email: form.email,
        details: {
          full_name: form.full_name,
          phone_number: form.phone_number,
          organization_name: form.organization_name,
          address: form.address,
          status: form.status,
        },
      };

      await updateProfile(payload);
      toast.success("Profile updated successfully!");
      refreshProfile();
    } catch (err) {
      console.error(err);

      const apiError = err?.response?.data;

      let message = "Failed to update profile";

      if (apiError?.message) {
        message = apiError.message;
      } else if (apiError?.detail) {
        message = apiError.detail;
      } else if (apiError?.email?.length) {
        message = apiError.email[0];
      } else if (apiError?.phone_number?.length) {
        message = apiError.phone_number[0];
      } else if (apiError?.details) {
        message = Object.values(apiError.details).flat().find(Boolean);
      }
      toast.error(message);
    }
  };

  const handlePasswordChange = (e) => {
    setPasswordForm({ ...passwordForm, [e.target.name]: e.target.value });
  };

  const handlePasswordSave = async () => {
    const { current_password, new_password, confirm_password } = passwordForm;

    if (!current_password || !new_password || !confirm_password) {
      toast.error("All fields are required!");
      return;
    }

    if (new_password !== confirm_password) {
      toast.error("New password and confirm password do not match!");
      return;
    }

    try {
      await changePassword({ current_password, new_password });
      toast.success("Password updated successfully!");
      setPasswordForm({
        current_password: "",
        new_password: "",
        confirm_password: "",
      });
    } catch (err) {
      console.error(err);

      const data = err?.response?.data;

      toast.error(
        data?.current_password?.[0] ||
          data?.new_password?.[0] ||
          data?.detail ||
          "Failed to update password",
      );
    }
  };

  const togglePassword = (field) => {
    setShowPassword((prev) => ({
      ...prev,
      [field]: !prev[field],
    }));
  };

  const handleImageUpload = async (e) => {
    const file = e.target.files?.[0];

    if (!file) return;

    try {
      setUploading(true);

      const formData = new FormData();

      // verify the field name from API docs
      formData.append("user_image", file);

      const response = await uploadProfileImage(formData);

      toast.success("Profile image updated successfully");
      await refreshProfile();
    } catch (error) {
      console.error("Upload Error:", error?.response?.data);
      toast.error(
        error?.response?.data?.detail ||
          error?.response?.data?.message ||
          "Failed to upload profile image",
      );
    } finally {
      setUploading(false);
    }
  };

  const validateField = (name, value) => {
    switch (name) {
      case "full_name":
        if (!value.trim()) return "Full Name is required";
        if (value.trim().length < 2)
          return "Full Name must be at least 2 characters";
        return "";
      case "email":
        if (!value) return "Email is required";

        return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(value)
          ? ""
          : "Please enter a valid email address";

      case "phone_number":
        if (!value) return "";

        return /^\(\d{3}\)\s\d{3}-\d{4}$/.test(value)
          ? ""
          : "Please enter a valid US phone number";

      default:
        return "";
    }
  };

  const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);

    if (digits.length <= 3) return digits;
    if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;

    return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
  };

  const handleBlur = (e) => {
    const { name, value } = e.target;

    setErrors((prev) => ({
      ...prev,
      [name]: validateField(name, value),
    }));
  };

  return (
    <Layout title="Profile Settings">
      <div className="pagerlink">
        <ul>
          <li>
            <Link href="/dashboard">Dashboard</Link>
          </li>
          <li>Profile Settings</li>
        </ul>
      </div>

      <div className="dshboardwhtepnel profilepnel">
        <div className="profileinform">
          <div className="media">
            {/* <div className="profileuser">
              <img src={assetPath("/assets/images/userimge.png")} alt="User" />
            </div> */}
            <div
              className="profileuser"
              onClick={() => fileInputRef.current?.click()}
              style={{
                position: "relative",
                width: "100px",
                height: "100px",
                borderRadius: "50%",
                overflow: "hidden",
                cursor: "pointer",
              }}
              onMouseEnter={(e) => {
                const overlay =
                  e.currentTarget.querySelector(".upload-overlay");
                if (overlay) overlay.style.opacity = "1";
              }}
              onMouseLeave={(e) => {
                const overlay =
                  e.currentTarget.querySelector(".upload-overlay");
                if (overlay) overlay.style.opacity = "0";
              }}
            >
              <img
                src={
                  profile?.details?.user_image
                    ? profile.details.user_image
                    : assetPath("/assets/images/userimge.png")
                }
                alt="User"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                  borderRadius: "50%",
                }}
              />

              <div
                className="upload-overlay"
                style={{
                  position: "absolute",
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  background: "rgba(0,0,0,0.5)",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "#fff",
                  opacity: 0,
                  transition: "opacity 0.3s ease",
                  borderRadius: "50%",
                }}
              >
                {uploading ? (
                  <span>Uploading...</span>
                ) : (
                  <>
                    <i
                      className="fa fa-camera"
                      style={{
                        fontSize: "28px",
                        marginBottom: "6px",
                      }}
                    />
                    <span
                      style={{
                        fontSize: "12px",
                        fontWeight: "500",
                      }}
                    >
                      Change Photo
                    </span>
                  </>
                )}
              </div>

              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                style={{ display: "none" }}
                onChange={handleImageUpload}
              />
            </div>
            <div className="media-object">
              <div className="prfletitle">
                <h3>{profile?.details?.full_name}</h3>
                <p>
                  Logged in as a <br /> 
                  {profile?.role_details?.map((role) => role.name).join(", ")}
                </p>
              </div>
              <div className="profileinfoicn">
                <h4>
                  <i>
                    <img src={assetPath("/assets/images/mailicn.png")} alt="" />
                  </i>
                  Mail ID
                </h4>
                <p>
                  <a href={`mailto:${profile?.email}`}>{profile?.email}</a>
                </p>
              </div>
              <div className="profileinfoicn">
                <h4>
                  <i>
                    <img src={assetPath("/assets/images/callicn.png")} alt="" />
                  </i>
                  Contact Number
                </h4>
                <p>
                  <a href={`tel:${profile?.details?.phone_number}`}>
                    {profile?.details?.phone_number}
                  </a>
                </p>
              </div>
              <div className="profileinfoicn">
                <h4>
                  <i>
                    <img
                      src={assetPath("/assets/images/locationicn.png")}
                      alt=""
                    />
                  </i>
                  Address
                </h4>
                <p>{profile?.details?.address || "Address not given yet"}</p>
              </div>
            </div>
          </div>
        </div>

        <div className="profilefrmpnel">
          <div className="profilefrmlnk">
            <ul className="nav nav-tabs" id="myTab" role="tablist">
              <li className="nav-item" role="presentation">
                <button
                  className="active"
                  id="home-tab"
                  data-bs-toggle="tab"
                  data-bs-target="#home-tab-pane"
                  type="button"
                  role="tab"
                  aria-controls="home-tab-pane"
                  aria-selected="true"
                >
                  Personal Info
                </button>
              </li>
              <li className="nav-item" role="presentation">
                <button
                  id="profile-tab"
                  data-bs-toggle="tab"
                  data-bs-target="#profile-tab-pane"
                  type="button"
                  role="tab"
                  aria-controls="profile-tab-pane"
                  aria-selected="false"
                >
                  Security
                </button>
              </li>
            </ul>
          </div>

          <div className="profilefrmtabopen">
            <div className="tab-content" id="myTabContent">
              {/* Personal Info Tab */}
              <div
                className="tab-pane fade show active"
                id="home-tab-pane"
                role="tabpanel"
                aria-labelledby="home-tab"
                tabIndex="0"
              >
                <div className="profilefrmshow">
                  <div className="profilefrmhder">
                    <h3>Personal Information</h3>
                    <p>Update your personal details and contact information</p>
                  </div>

                  <div className="row">
                    {/* FULL NAME */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>Full Name*</label>
                        <input
                          type="text"
                          name="full_name"
                          placeholder="Enter full name"
                          value={form.full_name}
                          onChange={handleChange}
                        />
                        {errors.full_name && (
                          <span className="text-danger d-block mt-1">
                            {errors.full_name}
                          </span>
                        )}
                      </div>
                    </div>

                    {/* PHONE NUMBER */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>Phone Number</label>
                        <input
                          type="text"
                          name="phone_number"
                          placeholder="(123) 456-7890"
                          value={form.phone_number}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        />

                        {errors.phone_number && (
                          <span className="text-danger d-block mt-1">
                            {errors.phone_number}
                          </span>
                        )}
                      </div>
                    </div>

                    {/* EMAIL */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>E-mail Address</label>
                        <input
                          type="email"
                          name="email"
                          placeholder="Enter email"
                          value={form.email}
                          onChange={handleChange}
                          onBlur={handleBlur}
                        />

                        {errors.email && (
                          <span className="text-danger d-block mt-1">
                            {errors.email}
                          </span>
                        )}
                      </div>
                    </div>

                    {/* ORGANIZATION NAME */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>Organization Name</label>
                        <input
                          type="text"
                          name="organization_name"
                          placeholder="Enter organization name"
                          value={form.organization_name}
                          onChange={handleChange}
                        />
                      </div>
                    </div>

                    {/* ADDRESS */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>Address</label>
                        <input
                          type="text"
                          name="address"
                          placeholder="Enter address"
                          value={form.address}
                          onChange={handleChange}
                        />
                      </div>
                    </div>

                    {/* STATUS */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <label>Select Status*</label>

                        <CustomSelect
                          name="status"
                          value={form.status}
                          onChange={handleChange}
                          placeholder="Select status"
                          options={[
                            { value: "available", label: "Available" },
                            { value: "busy", label: "Busy" },
                          ]}
                        />
                      </div>
                    </div>

                    {/* BUTTONS */}
                    <div className="col-12">
                      <div className="datafrmbtn">
                        <ul>
                          <li>
                            <button
                              className="canselbtn"
                              type="button"
                              onClick={() => setForm(profile.details)}
                            >
                              Cancel
                            </button>
                          </li>
                          <li>
                            <button type="button" onClick={handleSave}>
                              Save Changes
                            </button>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Security Tab */}
              <div
                className="tab-pane fade"
                id="profile-tab-pane"
                role="tabpanel"
                aria-labelledby="profile-tab"
                tabIndex="0"
              >
                <div className="profilefrmshow">
                  <div className="profilefrmhder">
                    <h3>Change password</h3>
                    <p>Update your password to keep your account secure</p>
                  </div>

                  <div className="row">
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <div className="pill-input">
                          <input
                            type={
                              showPassword.current_password
                                ? "text"
                                : "password"
                            }
                            name="current_password"
                            placeholder="Enter your current password"
                            value={passwordForm.current_password}
                            onChange={handlePasswordChange}
                          />
                          <button
                            type="button"
                            className="icon-btn"
                            onClick={() => togglePassword("current_password")}
                          >
                            <img
                              className="eye-open"
                              src={assetPath("/assets/images/eyeopen.png")}
                              alt="Show"
                              style={{
                                display: showPassword.current_password
                                  ? "none"
                                  : "inline",
                              }}
                            />
                            <img
                              className="eye-closed"
                              src={assetPath("/assets/images/eyeclose.png")}
                              alt="Hide"
                              style={{
                                display: showPassword.current_password
                                  ? "inline"
                                  : "none",
                              }}
                            />
                          </button>
                        </div>
                      </div>
                    </div>

                    {/* New Password */}
                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <div className="pill-input">
                          <input
                            type={
                              showPassword.new_password ? "text" : "password"
                            }
                            name="new_password"
                            placeholder="Enter your new password"
                            value={passwordForm.new_password}
                            onChange={handlePasswordChange}
                          />
                          <button
                            type="button"
                            className="icon-btn"
                            onClick={() => togglePassword("new_password")}
                            aria-label="toggle new password visibility"
                          >
                            <img
                              className="eye-open"
                              src={assetPath("/assets/images/eyeopen.png")}
                              alt="Show"
                              style={{
                                display: showPassword.new_password
                                  ? "none"
                                  : "inline",
                              }}
                            />
                            <img
                              className="eye-closed"
                              src={assetPath("/assets/images/eyeclose.png")}
                              alt="Hide"
                              style={{
                                display: showPassword.new_password
                                  ? "inline"
                                  : "none",
                              }}
                            />
                          </button>
                        </div>
                      </div>
                    </div>

                    <div className="col-lg-4 col-sm-6">
                      <div className="datafrm">
                        <div className="pill-input">
                          <input
                            type={
                              showPassword.confirm_password
                                ? "text"
                                : "password"
                            }
                            name="confirm_password"
                            placeholder="Confirm password"
                            value={passwordForm.confirm_password}
                            onChange={handlePasswordChange}
                          />
                          <button
                            type="button"
                            className="icon-btn"
                            onClick={() => togglePassword("confirm_password")}
                            aria-label="toggle confirm password visibility"
                          >
                            <img
                              className="eye-open"
                              src={assetPath("/assets/images/eyeopen.png")}
                              alt="Show"
                              style={{
                                display: showPassword.confirm_password
                                  ? "none"
                                  : "inline",
                              }}
                            />
                            <img
                              className="eye-closed"
                              src={assetPath("/assets/images/eyeclose.png")}
                              alt="Hide"
                              style={{
                                display: showPassword.confirm_password
                                  ? "inline"
                                  : "none",
                              }}
                            />
                          </button>
                        </div>
                      </div>
                    </div>

                    <div className="col-12">
                      <div className="datafrmbtn">
                        <ul>
                          <li>
                            <button className="canselbtn">Cancel</button>
                          </li>
                          <li>
                            <button type="button" onClick={handlePasswordSave}>
                              Save Changes
                            </button>
                          </li>
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              {/* End Security Tab */}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
}
