import React, { useState, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Container,
  Typography,
  Avatar,
  Button,
  TextField,
  Divider,
  Box,
  Stack,
  IconButton
} from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import CancelIcon from '@mui/icons-material/Cancel';
import SaveIcon from '@mui/icons-material/Save';

const Profile = () => {
  const navigate = useNavigate();
  const [preview, setPreview] = useState(null);
  const [selectedFile, setSelectedFile] = useState(null);
  const fileInputRef = useRef(null);

  const handleLogout = () => {
    localStorage.removeItem("authToken");
    navigate('/auth/login');
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setSelectedFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreview(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const triggerFileInput = () => {
    fileInputRef.current.click();
  };

  const handleCancel = () => {
    setPreview(null);
    setSelectedFile(null);
    fileInputRef.current.value = '';
  };

  const handleUpload = () => {
    if (!selectedFile) return;
    alert('Upload functionality would go here');
  };

  return (
    <Container maxWidth="md" sx={{ mt: 4 }}>
      <Typography variant="h4" gutterBottom>
        My Profile Settings
      </Typography>

      {/* Profile Photo Section */}
      <Box sx={{ mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          PROFILE PHOTO
        </Typography>
        <Stack direction="row" alignItems="center" spacing={3} sx={{ mb: 2 }}>
          <Box>
            {preview ? (
              <Avatar
                src={preview}
                alt="Profile Preview"
                sx={{ width: 100, height: 100 }}
              />
            ) : (
              <Avatar sx={{ width: 100, height: 100, bgcolor: 'grey.300' }} />
            )}
          </Box>
          <Box>
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileChange}
              accept="image/*"
              style={{ display: 'none' }}
            />
            <Button
              variant="outlined"
              startIcon={<CloudUploadIcon />}
              onClick={triggerFileInput}
            >
              Choose File
            </Button>
          </Box>
        </Stack>

        {/* Action buttons - shown only when an image is selected */}
        {preview && (
          <Stack direction="row" spacing={2} justifyContent="flex-end">
            <Button
              variant="outlined"
              startIcon={<CancelIcon />}
              onClick={handleCancel}
            >
              Cancel
            </Button>
            <Button
              variant="contained"
              startIcon={<SaveIcon />}
              onClick={handleUpload}
            >
              Upload
            </Button>
          </Stack>
        )}
      </Box>

      {/* Profile Form */}
      <Box component="form" sx={{ mb: 4 }}>
        <TextField
          label="Your Full Name"
          value="sysadmin"
          fullWidth
          margin="normal"
          InputProps={{
            readOnly: true,
          }}
        />
        
        <TextField
          label="Pronouns"
          placeholder="Enter Pronouns"
          fullWidth
          margin="normal"
        />
        
        <TextField
          label="Role"
          placeholder="Enter Role"
          fullWidth
          margin="normal"
        />
        
        <TextField
          label="Department or Team"
          placeholder="Enter Department"
          fullWidth
          margin="normal"
        />
        
        <TextField
          label="Email"
          value="sysadmin"
          fullWidth
          margin="normal"
          InputProps={{
            readOnly: true,
          }}
        />
        
        <TextField
          label="About Me"
          placeholder="Enter Description"
          fullWidth
          margin="normal"
          multiline
          rows={4}
        />
        
        <Button
          variant="contained"
          sx={{ mt: 2 }}
          onClick={() => navigate('/error404')}
        >
          Update Profile
        </Button>
      </Box>

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

      <Typography paragraph>
        <strong>Password:</strong> Change Password for your account{' '}
        <Link to="/admin/resetpassword">Change password</Link>
      </Typography>

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

      <Typography paragraph>
        <strong>Security:</strong> Logout of all sessions except this current browser{' '}
        <Button color="primary" onClick={handleLogout}>
          Logout other sessions
        </Button>
      </Typography>

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

      <Typography paragraph>
        <strong>Deactivation:</strong> Remove access to all organizations and workspace in CloudnSure{' '}
        <Button color="primary" onClick={handleLogout}>
          Deactivate account
        </Button>
      </Typography>
    </Container>
  );
};

export default Profile;