"use client";

import { useRef, useState, type KeyboardEvent, type ReactNode } from "react";

import Alert from "@mui/material/Alert";
import Avatar from "@mui/material/Avatar";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import Chip from "@mui/material/Chip";
import CircularProgress from "@mui/material/CircularProgress";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import InputAdornment from "@mui/material/InputAdornment";
import Paper from "@mui/material/Paper";
import SvgIcon from "@mui/material/SvgIcon";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import {
  alpha,
  useTheme,
  type SxProps,
  type Theme,
} from "@mui/material/styles";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { useAccountSetting } from "@/features/account-setting/hook/use-account-setting";

type UiLanguage = "en" | "km";

const accountText = {
  en: {
    profile: "Profile",
    uploadPhoto: "Upload Photo",
    accountStatus: "Account Status",
    active: "Active",
    memberSince: "Member Since",
    lastLogin: "Last Update",

    personalInfo: "Personal Information",
    personalInfoDesc: "Update your basic account information.",
    fullName: "Full Name",
    emailAddress: "Email Address",
    position: "Position",

    preferencesSmall: "Preferences",
    language: "Language",
    theme: "Theme",
    khmer: "Khmer",
    english: "English",
    lightMode: "Light Mode",
    darkMode: "Dark Mode",

    changeEmail: "Change Email",
    changeEmailDesc:
      "Update your email address. You may need to verify it by OTP.",
    newEmail: "New Email",
    currentPasswordForEmail: "Current Password",
    enterNewEmail: "Enter new email",
    enterPasswordForEmail: "Enter current password",
    changingEmail: "Changing email...",

    verifyOtp: "Verify Email OTP",
    verifyOtpDesc: "Enter the 6 digit code sent to your new email.",
    otpCode: "OTP Code",
    verifyCode: "Verify Code",
    verifyingCode: "Verifying...",
    resendCode: "Resend Code",
    resendingCode: "Resending...",
    backToEmail: "Back",
    otpSentTo: "OTP sent to",

    changePassword: "Change Password",
    changePasswordDesc: "Use a strong password to keep your account safe.",
    currentPassword: "Current Password",
    newPassword: "New Password",
    confirmNewPassword: "Confirm New Password",
    enterCurrentPassword: "Enter current password",
    enterNewPassword: "Enter new password",
    confirmNewPasswordPlaceholder: "Confirm new password",
    changingPassword: "Changing...",

    cancel: "Cancel",
    updateAccount: "Update Account",
    loadingAccount: "Loading account...",
    saving: "Saving...",
  },
  km: {
    profile: "ប្រវត្តិរូប",
    uploadPhoto: "ផ្ទុករូបថត",
    accountStatus: "ស្ថានភាពគណនី",
    active: "សកម្ម",
    memberSince: "ចូលជាសមាជិកតាំងពី",
    lastLogin: "កែប្រែចុងក្រោយ",

    personalInfo: "ព័ត៌មានផ្ទាល់ខ្លួន",
    personalInfoDesc: "ធ្វើបច្ចុប្បន្នភាពព័ត៌មានគណនីមូលដ្ឋានរបស់អ្នក។",
    fullName: "ឈ្មោះពេញ",
    emailAddress: "អ៊ីមែល",
    position: "តួនាទី",

    preferencesSmall: "ចំណូលចិត្ត",
    language: "ភាសា",
    theme: "រូបរាង",
    khmer: "ខ្មែរ",
    english: "អង់គ្លេស",
    lightMode: "របៀបភ្លឺ",
    darkMode: "របៀបងងឹត",

    changeEmail: "ប្តូរអ៊ីមែល",
    changeEmailDesc:
      "ធ្វើបច្ចុប្បន្នភាពអាសយដ្ឋានអ៊ីមែលរបស់អ្នក។ អាចត្រូវការបញ្ជាក់ OTP។",
    newEmail: "អ៊ីមែលថ្មី",
    currentPasswordForEmail: "ពាក្យសម្ងាត់បច្ចុប្បន្ន",
    enterNewEmail: "បញ្ចូលអ៊ីមែលថ្មី",
    enterPasswordForEmail: "បញ្ចូលពាក្យសម្ងាត់បច្ចុប្បន្ន",
    changingEmail: "កំពុងប្តូរអ៊ីមែល...",

    verifyOtp: "បញ្ជាក់ OTP អ៊ីមែល",
    verifyOtpDesc: "បញ្ចូលលេខកូដ 6 ខ្ទង់ ដែលបានផ្ញើទៅអ៊ីមែលថ្មីរបស់អ្នក។",
    otpCode: "លេខកូដ OTP",
    verifyCode: "បញ្ជាក់កូដ",
    verifyingCode: "កំពុងបញ្ជាក់...",
    resendCode: "ផ្ញើកូដម្តងទៀត",
    resendingCode: "កំពុងផ្ញើ...",
    backToEmail: "ត្រឡប់ក្រោយ",
    otpSentTo: "OTP បានផ្ញើទៅ",

    changePassword: "ប្តូរពាក្យសម្ងាត់",
    changePasswordDesc:
      "ប្រើពាក្យសម្ងាត់ខ្លាំង ដើម្បីរក្សាគណនីរបស់អ្នកឱ្យមានសុវត្ថិភាព។",
    currentPassword: "ពាក្យសម្ងាត់បច្ចុប្បន្ន",
    newPassword: "ពាក្យសម្ងាត់ថ្មី",
    confirmNewPassword: "បញ្ជាក់ពាក្យសម្ងាត់ថ្មី",
    enterCurrentPassword: "បញ្ចូលពាក្យសម្ងាត់បច្ចុប្បន្ន",
    enterNewPassword: "បញ្ចូលពាក្យសម្ងាត់ថ្មី",
    confirmNewPasswordPlaceholder: "បញ្ជាក់ពាក្យសម្ងាត់ថ្មី",
    changingPassword: "កំពុងប្តូរ...",

    cancel: "បោះបង់",
    updateAccount: "ធ្វើបច្ចុប្បន្នភាពគណនី",
    loadingAccount: "កំពុងទាញយកគណនី...",
    saving: "កំពុងរក្សាទុក...",
  },
} as const;

const labelSx: SxProps<Theme> = {
  mb: 0.8,
  fontSize: 13,
  fontWeight: 700,
  color: "text.secondary",
};

const primaryButtonSx: SxProps<Theme> = {
  height: 46,
  width: { xs: "100%", sm: 230 },
  borderRadius: "10px",
  textTransform: "none",
  fontWeight: 800,
  bgcolor: "#0284c7",
  color: "#ffffff",
  boxShadow: "none",
  "&:hover": {
    bgcolor: "#0369a1",
    boxShadow: "none",
  },
  "&:disabled": {
    bgcolor: "#94a3b8",
    color: "#ffffff",
  },
};

function normalizeLanguage(language?: string): UiLanguage {
  return language === "en" ? "en" : "km";
}

function formatDateTime(value?: string) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return "-";
  }

  return date.toLocaleString();
}

function getInitials(name: string) {
  if (!name) {
    return "U";
  }

  return name
    .split(" ")
    .map((item) => item[0])
    .join("")
    .slice(0, 2)
    .toUpperCase();
}

function UserIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M12 12c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5Zm0 2c-3.33 0-10 1.67-10 5v1.5c0 .83.67 1.5 1.5 1.5h17c.83 0 1.5-.67 1.5-1.5V19c0-3.33-6.67-5-10-5Z"
      />
    </SvgIcon>
  );
}

function CameraIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M9 3 7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2h-3.17L15 3H9Zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5Z"
      />
    </SvgIcon>
  );
}

function UploadIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M5 20h14v-2H5v2ZM11 16h2V8.83l2.59 2.58L17 10l-5-5-5 5 1.41 1.41L11 8.83V16Z"
      />
    </SvgIcon>
  );
}

function EmailIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2Zm0 4-8 5-8-5V6l8 5 8-5v2Z"
      />
    </SvgIcon>
  );
}

function LockIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2ZM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6Z"
      />
    </SvgIcon>
  );
}

function EyeIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5Zm0 12.5c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5Z"
      />
    </SvgIcon>
  );
}

function SaveIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4ZM12 19c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3ZM6 8V5h9v3H6Z"
      />
    </SvgIcon>
  );
}

function CalendarIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M7 2h2v2h6V2h2v2h1c1.1 0 2 .9 2 2v14c0 1.1-.9 2-2 2H6c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h1V2Zm11 8H6v10h12V10Z"
      />
    </SvgIcon>
  );
}

function ClockIcon() {
  return (
    <SvgIcon fontSize="small" viewBox="0 0 24 24">
      <path
        fill="currentColor"
        d="M12 1.75C6.34 1.75 1.75 6.34 1.75 12S6.34 22.25 12 22.25 22.25 17.66 22.25 12 17.66 1.75 12 1.75Zm.75 10.56 4.22 2.51-.75 1.23-4.97-2.96V6.75h1.5v5.56Z"
      />
    </SvgIcon>
  );
}

function SectionHeader({
  icon,
  title,
  subtitle,
  color,
}: {
  icon: ReactNode;
  title: string;
  subtitle: string;
  color: string;
}) {
  const theme = useTheme();

  return (
    <Box sx={{ display: "flex", alignItems: "flex-start", gap: 1.5, mb: 2.5 }}>
      <Box
        sx={{
          width: 44,
          height: 44,
          borderRadius: "14px",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color,
          bgcolor: alpha(color, theme.palette.mode === "dark" ? 0.18 : 0.1),
          flexShrink: 0,
        }}
      >
        {icon}
      </Box>

      <Box>
        <Typography
          sx={{
            fontSize: 20,
            fontWeight: 800,
            color: "text.primary",
            lineHeight: 1.2,
          }}
        >
          {title}
        </Typography>

        <Typography sx={{ mt: 0.4, fontSize: 13, color: "text.secondary" }}>
          {subtitle}
        </Typography>
      </Box>
    </Box>
  );
}

export default function AccountSettingPage() {
  const theme = useTheme();

  const appLanguage = useAppLanguage() as {
    language?: "en" | "km" | "kh";
    setLanguage?: (language: "en" | "km" | "kh") => void;
    changeLanguage?: (language: "en" | "km" | "kh") => void;
  };

  const {
    profile,
    form,
    avatarPreviewUrl,
    passwordForm,
    emailForm,
    emailChangeStep,
    emailOtp,
    pendingEmail,
    loading,
    saving,
    changingPassword,
    changingEmail,
    verifyingEmail,
    resendingEmailOtp,
    error,
    successMessage,
    handleInputChange,
    handlePasswordInputChange,
    handleEmailInputChange,
    handleAvatarFileChange,
    handleEmailOtpChange,
    handleBackToEmailForm,
    handleUpdateProfile,
    handleChangePassword,
    handleChangeEmail,
    handleResendEmailOtp,
    handleVerifyEmailOtp,
  } = useAccountSetting();

  const language = normalizeLanguage(appLanguage.language);
  const text = accountText[language];

  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [showEmailPassword, setShowEmailPassword] = useState(false);

  const otpInputRefs = useRef<Array<HTMLInputElement | null>>([]);

  const focusOtpInput = (index: number) => {
    window.setTimeout(() => {
      otpInputRefs.current[index]?.focus();
      otpInputRefs.current[index]?.select();
    }, 0);
  };

  const handleOtpChange = (index: number, value: string) => {
    const digits = value.replace(/\D/g, "").slice(0, 6);

    handleEmailOtpChange(index, digits);

    if (!digits) {
      return;
    }

    if (digits.length > 1) {
      focusOtpInput(Math.min(digits.length, 5));
      return;
    }

    if (index < 5) {
      focusOtpInput(index + 1);
    }
  };

  const handleOtpPaste = (value: string) => {
    const digits = value.replace(/\D/g, "").slice(0, 6);

    if (!digits) {
      return;
    }

    handleEmailOtpChange(0, digits);
    focusOtpInput(Math.min(digits.length, 5));
  };

  const handleOtpKeyDown = (
    index: number,
    event: KeyboardEvent<HTMLDivElement>,
  ) => {
    if (event.key === "Backspace" && !emailOtp[index] && index > 0) {
      event.preventDefault();
      handleEmailOtpChange(index - 1, "");
      focusOtpInput(index - 1);
    }

    if (event.key === "ArrowLeft" && index > 0) {
      event.preventDefault();
      focusOtpInput(index - 1);
    }

    if (event.key === "ArrowRight" && index < 5) {
      event.preventDefault();
      focusOtpInput(index + 1);
    }
  };

  const cardSx: SxProps<Theme> = {
    borderRadius: "20px",
    border: `1px solid ${theme.palette.divider}`,
    boxShadow:
      theme.palette.mode === "dark"
        ? "0 18px 48px rgba(0,0,0,0.28)"
        : "0 12px 34px rgba(15,23,42,0.06)",
    bgcolor: "background.paper",
  };

  const inputSx: SxProps<Theme> = {
    "& .MuiOutlinedInput-root": {
      borderRadius: "10px",
      fontSize: 14,
      bgcolor:
        theme.palette.mode === "dark"
          ? alpha(theme.palette.common.white, 0.03)
          : "#fff",
    },
    "& .MuiOutlinedInput-input": {
      py: 1.35,
    },
  };

  const otpInputSx: SxProps<Theme> = {
    width: "100%",
    minWidth: 0,
    "& .MuiOutlinedInput-root": {
      borderRadius: "10px",
      bgcolor:
        theme.palette.mode === "dark"
          ? alpha(theme.palette.common.white, 0.03)
          : "#fff",
    },
    "& .MuiOutlinedInput-input": {
      p: 0,
      height: { xs: 48, sm: 56 },
      textAlign: "center",
      fontSize: { xs: 18, sm: 22 },
      fontWeight: 800,
    },
  };


  if (loading) {
    return (
      <Box
        sx={{
          minHeight: 360,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 1.5,
        }}
      >
        <CircularProgress size={24} />
        <Typography>{text.loadingAccount}</Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ width: "100%", minHeight: "100vh", p: { xs: 2, md: 3 } }}>
      {error ? (
        <Alert severity="error" sx={{ mb: 2, borderRadius: 2 }}>
          {error}
        </Alert>
      ) : null}

      {successMessage ? (
        <Alert severity="success" sx={{ mb: 2, borderRadius: 2 }}>
          {successMessage}
        </Alert>
      ) : null}

      <Box
        sx={{
          display: "grid",
          gridTemplateColumns: { xs: "1fr", lg: "340px minmax(0, 1fr)" },
          gap: 2.5,
          alignItems: "stretch",
        }}
      >
        <Paper elevation={0} sx={{ ...cardSx, p: 3, height: "100%" }}>
          <Typography sx={{ fontSize: 18, fontWeight: 800, mb: 3 }}>
            {text.profile}
          </Typography>

          <Box
            sx={{
              display: "flex",
              alignItems: "center",
              flexDirection: "column",
              textAlign: "center",
            }}
          >
            <Box sx={{ position: "relative" }}>
              <Avatar
                src={avatarPreviewUrl || form.avatar || undefined}
                alt={form.name || "User"}
                sx={{
                  width: 120,
                  height: 120,
                  fontSize: 42,
                  fontWeight: 800,
                  bgcolor: "#dbeafe",
                  color: "#0f766e",
                }}
              >
                {getInitials(form.name)}
              </Avatar>

              <Box
                sx={{
                  position: "absolute",
                  right: 4,
                  bottom: 6,
                  width: 38,
                  height: 38,
                  borderRadius: "50%",
                  bgcolor: "#0891b2",
                  color: "#fff",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  border: "3px solid",
                  borderColor: "background.paper",
                }}
              >
                <CameraIcon />
              </Box>
            </Box>

            <Typography sx={{ mt: 1.8, fontSize: 24, fontWeight: 800 }}>
              {form.name || "User"}
            </Typography>

            <Typography sx={{ fontSize: 14, color: "text.secondary" }}>
              {form.position || "-"}
            </Typography>

            <Button
              component="label"
              variant="outlined"
              startIcon={<UploadIcon />}
              disabled={saving}
              sx={{
                mt: 2.5,
                width: 190,
                height: 44,
                borderRadius: "10px",
                textTransform: "none",
                fontWeight: 800,
                color: "text.primary",
                borderColor: theme.palette.divider,
              }}
            >
              {text.uploadPhoto}
              <Box
                component="input"
                type="file"
                accept="image/jpeg,image/png,image/svg+xml"
                onChange={handleAvatarFileChange}
                sx={{ display: "none" }}
              />
            </Button>
          </Box>

          <Divider sx={{ my: 3 }} />

          <Typography
            sx={{ fontSize: 13, fontWeight: 800, color: "text.secondary" }}
          >
            {text.accountStatus}
          </Typography>

          <Chip
            label={text.active}
            size="small"
            sx={{
              mt: 1.2,
              height: 34,
              px: 1,
              borderRadius: "10px",
              bgcolor: alpha("#22c55e", 0.12),
              color: "#16a34a",
              fontWeight: 800,
              "&::before": {
                content: '""',
                width: 9,
                height: 9,
                borderRadius: "50%",
                bgcolor: "#22c55e",
                ml: 1,
              },
            }}
          />

          <Divider sx={{ my: 2.8 }} />

          <Box sx={{ display: "flex", flexDirection: "column", gap: 2.4 }}>
            <Box>
              <Typography
                sx={{ fontSize: 13, fontWeight: 800, color: "text.secondary" }}
              >
                {text.memberSince}
              </Typography>

              <Box
                sx={{ display: "flex", alignItems: "center", gap: 1, mt: 1 }}
              >
                <CalendarIcon />

                <Typography sx={{ fontSize: 14 }}>
                  {formatDateTime(profile?.createdAt)}
                </Typography>
              </Box>
            </Box>

            <Box>
              <Typography
                sx={{ fontSize: 13, fontWeight: 800, color: "text.secondary" }}
              >
                {text.lastLogin}
              </Typography>

              <Box
                sx={{ display: "flex", alignItems: "center", gap: 1, mt: 1 }}
              >
                <ClockIcon />

                <Typography sx={{ fontSize: 14 }}>
                  {formatDateTime(profile?.updatedAt)}
                </Typography>
              </Box>
            </Box>
          </Box>

          <Divider sx={{ my: 2.8 }} />
        </Paper>

        <Box
          sx={{
            minWidth: 0,
            display: "flex",
            flexDirection: "column",
            gap: 2.5,
          }}
        >
          <Paper elevation={0} sx={{ ...cardSx, p: { xs: 2.5, md: 3 } }}>
            <SectionHeader
              icon={<UserIcon />}
              title={text.personalInfo}
              subtitle={text.personalInfoDesc}
              color="#2563eb"
            />

            <Box
              sx={{
                display: "grid",
                gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
                gap: 2,
              }}
            >
              <Box>
                <Typography sx={labelSx}>{text.fullName}</Typography>

                <TextField
                  fullWidth
                  value={form.name}
                  onChange={handleInputChange("name")}
                  sx={inputSx}
                />
              </Box>

              <Box>
                <Typography sx={labelSx}>{text.emailAddress}</Typography>

                <TextField fullWidth value={form.email} disabled sx={inputSx} />
              </Box>

              <Box sx={{ gridColumn: { xs: "auto", md: "1 / -1" } }}>
                <Typography sx={labelSx}>{text.position}</Typography>

                <TextField
                  fullWidth
                  value={form.position}
                  onChange={handleInputChange("position")}
                  sx={inputSx}
                />
              </Box>
            </Box>
          </Paper>

          <Paper elevation={0} sx={{ ...cardSx, p: { xs: 2.5, md: 3 } }}>
            {emailChangeStep === "form" ? (
              <>
                <SectionHeader
                  icon={<EmailIcon />}
                  title={text.changeEmail}
                  subtitle={text.changeEmailDesc}
                  color="#0284c7"
                />

                <Box
                  sx={{
                    display: "grid",
                    gridTemplateColumns: { xs: "1fr", md: "1fr 1fr" },
                    gap: 2,
                  }}
                >
                  <Box>
                    <Typography sx={labelSx}>{text.newEmail}</Typography>

                    <TextField
                      fullWidth
                      type="email"
                      placeholder={text.enterNewEmail}
                      value={emailForm.newEmail}
                      onChange={handleEmailInputChange("newEmail")}
                      sx={inputSx}
                    />
                  </Box>

                  <Box>
                    <Typography sx={labelSx}>
                      {text.currentPasswordForEmail}
                    </Typography>

                    <TextField
                      fullWidth
                      type={showEmailPassword ? "text" : "password"}
                      placeholder={text.enterPasswordForEmail}
                      value={emailForm.currentPassword}
                      onChange={handleEmailInputChange("currentPassword")}
                      sx={inputSx}
                      slotProps={{
                        input: {
                          endAdornment: (
                            <InputAdornment position="end">
                              <IconButton
                                size="small"
                                onClick={() =>
                                  setShowEmailPassword((value) => !value)
                                }
                              >
                                <EyeIcon />
                              </IconButton>
                            </InputAdornment>
                          ),
                        },
                      }}
                    />
                  </Box>
                </Box>

                <Box
                  sx={{
                    mt: 2.2,
                    display: "flex",
                    justifyContent: "flex-start",
                  }}
                >
                  <Button
                    variant="contained"
                    disabled={changingEmail}
                    onClick={handleChangeEmail}
                    sx={primaryButtonSx}
                  >
                    {changingEmail ? text.changingEmail : text.changeEmail}
                  </Button>
                </Box>
              </>
            ) : (
              <>
                <SectionHeader
                  icon={<EmailIcon />}
                  title={text.verifyOtp}
                  subtitle={text.verifyOtpDesc}
                  color="#0284c7"
                />

                <Box
                  sx={{
                    width: { xs: "100%", md: "calc((100% - 16px) / 2)" },
                  }}
                >
                  <Typography sx={labelSx}>{text.otpCode}</Typography>

                  <Box
                    sx={{
                      display: "grid",
                      gridTemplateColumns: "repeat(6, minmax(0, 1fr))",
                      gap: { xs: 0.75, sm: 1 },
                      mb: 1.2,
                      width: "100%",
                    }}
                  >
                    {emailOtp.map((digit, index) => (
                      <TextField
                        key={index}
                        value={digit}
                        inputRef={(element) => {
                          otpInputRefs.current[index] = element;
                        }}
                        onChange={(event) =>
                          handleOtpChange(index, event.target.value)
                        }
                        onPaste={(event) => {
                          event.preventDefault();
                          handleOtpPaste(event.clipboardData.getData("text"));
                        }}
                        onKeyDown={(event) => handleOtpKeyDown(index, event)}
                        sx={otpInputSx}
                        slotProps={{
                          htmlInput: {
                            maxLength: 6,
                            inputMode: "numeric",
                            pattern: "[0-9]*",
                            autoComplete: index === 0 ? "one-time-code" : "off",
                            "aria-label": `OTP digit ${index + 1}`,
                          },
                        }}
                      />
                    ))}
                  </Box>

                  {pendingEmail ? (
                    <Typography
                      sx={{
                        mb: 2,
                        fontSize: 13,
                        color: "text.secondary",
                      }}
                    >
                      {text.otpSentTo}: {pendingEmail}
                    </Typography>
                  ) : null}

                  <Button
                    variant="contained"
                    disabled={verifyingEmail}
                    onClick={handleVerifyEmailOtp}
                    sx={{
                      ...primaryButtonSx,
                      width: "100%",
                    }}
                  >
                    {verifyingEmail ? text.verifyingCode : text.verifyCode}
                  </Button>

                  <Box
                    sx={{
                      mt: 1.5,
                      display: "flex",
                      justifyContent: "space-between",
                      gap: 1,
                      width: "100%",
                    }}
                  >
                    <Button
                      variant="text"
                      disabled={verifyingEmail || resendingEmailOtp}
                      onClick={handleBackToEmailForm}
                      sx={{
                        textTransform: "none",
                        fontWeight: 800,
                        color: "text.secondary",
                      }}
                    >
                      {text.backToEmail}
                    </Button>

                    <Button
                      variant="text"
                      disabled={verifyingEmail || resendingEmailOtp}
                      onClick={handleResendEmailOtp}
                      sx={{
                        textTransform: "none",
                        fontWeight: 800,
                        color: "#0284c7",
                      }}
                    >
                      {resendingEmailOtp ? text.resendingCode : text.resendCode}
                    </Button>
                  </Box>
                </Box>
              </>
            )}
          </Paper>

          <Paper elevation={0} sx={{ ...cardSx, p: { xs: 2.5, md: 3 } }}>
            <SectionHeader
              icon={<LockIcon />}
              title={text.changePassword}
              subtitle={text.changePasswordDesc}
              color="#0284c7"
            />

            <Box
              sx={{
                width: { xs: "100%", md: "calc((100% - 16px) / 2)" },
                display: "grid",
                gridTemplateColumns: "1fr",
                gap: 2,
              }}
            >
              <Box>
                <Typography sx={labelSx}>{text.currentPassword}</Typography>

                <TextField
                  fullWidth
                  type={showCurrentPassword ? "text" : "password"}
                  placeholder={text.enterCurrentPassword}
                  value={passwordForm.currentPassword}
                  onChange={handlePasswordInputChange("currentPassword")}
                  sx={inputSx}
                  slotProps={{
                    input: {
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            size="small"
                            onClick={() =>
                              setShowCurrentPassword((value) => !value)
                            }
                          >
                            <EyeIcon />
                          </IconButton>
                        </InputAdornment>
                      ),
                    },
                  }}
                />
              </Box>

              <Box>
                <Typography sx={labelSx}>{text.newPassword}</Typography>

                <TextField
                  fullWidth
                  type={showNewPassword ? "text" : "password"}
                  placeholder={text.enterNewPassword}
                  value={passwordForm.newPassword}
                  onChange={handlePasswordInputChange("newPassword")}
                  sx={inputSx}
                  slotProps={{
                    input: {
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            size="small"
                            onClick={() =>
                              setShowNewPassword((value) => !value)
                            }
                          >
                            <EyeIcon />
                          </IconButton>
                        </InputAdornment>
                      ),
                    },
                  }}
                />
              </Box>

              <Box>
                <Typography sx={labelSx}>{text.confirmNewPassword}</Typography>

                <TextField
                  fullWidth
                  type={showConfirmPassword ? "text" : "password"}
                  placeholder={text.confirmNewPasswordPlaceholder}
                  value={passwordForm.confirmPassword}
                  onChange={handlePasswordInputChange("confirmPassword")}
                  sx={inputSx}
                  slotProps={{
                    input: {
                      endAdornment: (
                        <InputAdornment position="end">
                          <IconButton
                            size="small"
                            onClick={() =>
                              setShowConfirmPassword((value) => !value)
                            }
                          >
                            <EyeIcon />
                          </IconButton>
                        </InputAdornment>
                      ),
                    },
                  }}
                />
              </Box>

              <Button
                variant="contained"
                disabled={changingPassword}
                onClick={handleChangePassword}
                sx={primaryButtonSx}
              >
                {changingPassword ? text.changingPassword : text.changePassword}
              </Button>
            </Box>
          </Paper>
        </Box>
      </Box>

      <Box
        sx={{
          mt: 2.5,
          display: "flex",
          justifyContent: "flex-end",
          gap: 1.5,
        }}
      >
        <Button
          variant="outlined"
          disabled={saving}
          sx={{
            height: 46,
            minWidth: 120,
            borderRadius: "10px",
            textTransform: "none",
            fontWeight: 800,
            color: "text.primary",
            borderColor: theme.palette.divider,
          }}
        >
          {text.cancel}
        </Button>

        <Button
          variant="contained"
          startIcon={saving ? <CircularProgress size={16} /> : <SaveIcon />}
          disabled={saving}
          onClick={handleUpdateProfile}
          sx={{
            height: 46,
            minWidth: 180,
            borderRadius: "10px",
            textTransform: "none",
            fontWeight: 800,
            bgcolor: "#0284c7",
            color: "#ffffff",
            boxShadow: "none",
            "&:hover": {
              bgcolor: "#0369a1",
              boxShadow: "none",
            },
            "&:disabled": {
              bgcolor: "#94a3b8",
              color: "#ffffff",
            },
          }}
        >
          {saving ? text.saving : text.updateAccount}
        </Button>
      </Box>
    </Box>
  );
}
