"use client";

import React, { useState } from "react";
import { Paper, Typography } from "@mui/material";
import { ChangePassword } from "@/app/features/Auth/ChangePassword/ChangePassword";
import { RootState } from "@/app/redux/store";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch } from "@/app/redux/types";
import { changePassword } from "@/app/redux/auth/authSlice";

const SettingsAccountSecurity: React.FC = () => {
  const [submitting, setSubmitting] = useState(false);
  const user = useSelector((state: RootState) => state.auth.user);
  const dispatch = useDispatch<AppDispatch>();

  const handleChangePassword = async (passwordData: {
    currentPassword?: string;
    newPassword: string;
  }) => {
    try {
      setSubmitting(true);

      if (!user?.email) {
        throw new Error("User email not available");
      }

      await dispatch(
        changePassword({
          email: user.email,
          newPassword: passwordData.newPassword,
          currentPassword: passwordData.currentPassword,
        })
      );

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      // Error handling is now done by the epic
      console.error("Password change error:", err);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Paper elevation={1} sx={{ p: 3, maxWidth: 520 }}>
      <Typography variant="subtitle1" sx={{ mb: 2 }}>
        Account Security
      </Typography>
      <ChangePassword
        isUserChange={true}
        open={!submitting}
        onClose={() => {}}
        onSubmit={handleChangePassword}
      />
    </Paper>
  );
};

export default SettingsAccountSecurity;
