import * as React from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  IconButton,
  CircularProgress,
  Avatar,
  Alert,
} from '@mui/material';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import { useAuth } from '../providers/Author';

interface ProfileProps {
  onBack: () => void;
}

export default function Profile({ onBack }: ProfileProps) {
  const { currentUser, loading, error, logout, updateProfile } = useAuth();
  const [formData, setFormData] = React.useState({
    username: currentUser?.username || '',
    name: currentUser?.name || '',
    email: currentUser?.email || '',
    avatar: currentUser?.avatar || '',
  });
  const [success, setSuccess] = React.useState<string | null>(null);
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (currentUser)  setFormData(currentUser);
  }, [currentUser]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSave = async () => {
    if (!currentUser) return;

    try {
      setSaving(true);
      setSuccess(null);

      const updatedUser = { ...currentUser, ...formData };
      console.log('updatedUser');
      console.log(updatedUser);
      const updated = await updateProfile(updatedUser);

      if (updated) setSuccess('Profile updated successfully');
    } catch (err: any) {
      console.error('Failed to update profile:', err);
    } finally {
      setSaving(false);
    }
  };

  const handleLogout = async () => {
    logout()
  }

  if (!currentUser) {
    return (
      <Box
        sx={{
          maxWidth: 400,
          mx: 'auto',
          mt: 8,
          p: 4,
          borderRadius: 3,
          boxShadow: 3,
          bgcolor: 'background.paper',
        }}
      >
        <Typography variant="h6" align="center">
          You must be logged in to view your profile.
        </Typography>
        <Button fullWidth variant="outlined" sx={{ mt: 2 }} onClick={onBack}>
          Back
        </Button>
      </Box>
    );
  }

  return (
    <Box
      sx={{
        maxWidth: 500,
        mx: 'auto',
        mt: 8,
        p: 4,
        borderRadius: 3,
        boxShadow: 3,
        bgcolor: 'background.paper',
      }}
    >
      <IconButton onClick={onBack} sx={{ mb: 2 }}>
        <ArrowBackRoundedIcon />
      </IconButton>

      <Typography variant="h4" fontWeight="bold" gutterBottom>
        Profile
      </Typography>

      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 3 }}>
        <Avatar
          src={formData.avatar}
          alt={formData.name || formData.username}
          sx={{ width: 64, height: 64 }}
        />
        <TextField
          label="Avatar URL"
          name="avatar"
          fullWidth
          value={formData.avatar}
          onChange={handleChange}
        />
      </Box>

      <TextField
        fullWidth
        label="Username"
        name="username"
        margin="normal"
        value={formData.username}
        onChange={handleChange}
      />
      <TextField
        fullWidth
        label="Full Name"
        name="name"
        margin="normal"
        value={formData.name}
        onChange={handleChange}
      />
      <TextField
        fullWidth
        label="Email"
        name="email"
        type="email"
        margin="normal"
        value={formData.email}
        onChange={handleChange}
      />

      {error && (
        <Alert severity="error" sx={{ mt: 2 }}>
          {error}
        </Alert>
      )}
      {success && (
        <Alert severity="success" sx={{ mt: 2 }}>
          {success}
        </Alert>
      )}

      <Button
        fullWidth
        variant="contained"
        color="primary"
        sx={{ mt: 3 }}
        disabled={saving || loading}
        onClick={handleSave}
      >
        {saving ? <CircularProgress size={24} color="inherit" /> : 'Save Changes'}
      </Button>
      <Button
        fullWidth
        variant="contained"
        color="error"
        sx={{ mt: 3 }}
        onClick={handleLogout}
      >
        Logout
      </Button>
    </Box>
  );
}
