"use client";

import React, { useState, useEffect } from "react";
import {
  Paper,
  Typography,
  Box,
  TextField,
  Divider,
  Button,
} from "@mui/material";
import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "@/app/redux/store";
import { updateUserDetails } from "@/app/redux/auth/authSlice";

const SettingsPersonalInfo: React.FC = () => {
  const user = useSelector((state: RootState) => state.auth.user);
  const dispatch = useDispatch<AppDispatch>();

  const [formData, setFormData] = useState({
    first_name: "",
    last_name: "",
    username: "",
    email: "",
  });

  // Initialize form fields from Redux user data
  useEffect(() => {
    if (user) {
      setFormData({
        first_name: user.firstName ?? "",
        last_name: user.lastName ?? "",
        username: user.username ?? "",
        email: user.email ?? "",
      });
    }
  }, [user]);

  // Generic change handler
  const handleChange =
    (field: keyof typeof formData) =>
    (e: React.ChangeEvent<HTMLInputElement>) => {
      setFormData(prev => ({ ...prev, [field]: e.target.value }));
    };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    handleUpdateUserDetails();
  };

  const handleUpdateUserDetails = () => {
    dispatch(updateUserDetails({ id: user?.id ?? "", updates: formData }));
  };

  return (
    <Paper elevation={1} sx={{ p: 3, maxWidth: 720 }}>
      <Typography variant="subtitle1" sx={{ mb: 2 }}>
        Personal Info
      </Typography>

      <Box
        component="form"
        onSubmit={handleSave}
        sx={{ display: "flex", flexDirection: "column", gap: 2 }}
      >
        <TextField
          label="First Name"
          value={formData.first_name}
          onChange={handleChange("first_name")}
          fullWidth
        />
        <TextField
          label="Last Name"
          value={formData.last_name}
          onChange={handleChange("last_name")}
          fullWidth
        />
        <TextField
          label="Username"
          value={formData.username}
          onChange={handleChange("username")}
          fullWidth
        />
        <TextField
          disabled={true}
          label="Email"
          type="email"
          value={formData.email}
          onChange={handleChange("email")}
          fullWidth
        />
        <Divider sx={{ my: 1 }} />
        <Button
          type="submit"
          variant="contained"
          sx={{ alignSelf: "flex-start" }}
        >
          Save Changes
        </Button>
      </Box>
    </Paper>
  );
};

export default SettingsPersonalInfo;
