import * as React from 'react';
import {
  Box,
  TextField,
  Button,
  Typography,
  IconButton,
  CircularProgress,
  Alert,
} from '@mui/material';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import { useAuth as useAuthor } from '../providers/Author';
import { useAuth } from '../../../auth/src';
import { useUpload } from "../providers/Upload";
import ImageUploadField from './ImageUploadField';
import { ProfileProps } from '../types/props';

export default function Profile({
  onBack
}: ProfileProps) {
  const { logout } = useAuth();
  const { currentUser, updateProfile, loading, error } = useAuthor();

  const { uploadFile } = useUpload();
  const [formData, setFormData] = React.useState({
    username: currentUser?.username || '',
    name: currentUser?.name || '',
    email: currentUser?.email || '',
    avatar: currentUser?.avatar || '',
  });

  const [uploadingAvatar, setUploadingAvatar] = React.useState(false);
  const [success, setSuccess] = React.useState<string | null>(null);
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    if (currentUser) setFormData(currentUser);
    console.log("Current User:", currentUser);
  }, [currentUser]);

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

  const handleAvatarUpload = async (file: File) => {
    setUploadingAvatar(true);

    try {
      const avatar = await uploadFile(file);
      if (avatar) {
        setFormData((prev) => ({ ...prev, avatar: avatar }));
      }
    } catch (err) {
      console.error("Avatar upload failed:", err);
    } finally {
      setUploadingAvatar(false);
    }
  };

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

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

      const updatedUser = { ...currentUser, ...formData };
      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>

      <ImageUploadField
        label="Upload Avatar"
        value={formData.avatar}
        uploading={uploadingAvatar}
        onUpload={handleAvatarUpload}
        size={64}
      />

      <TextField
        fullWidth
        label="Username"
        name="username"
        margin="normal"
        disabled={true}
        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>
  );
}
