import React, { useContext, useState } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Button,
  Grid,
  TextField,
  Box,
  Alert,
  IconButton,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';
import { UserAPI } from 'types';
import { AccountContext } from 'contexts/AccountContext';

interface ProfileCardProps {
  user: UserAPI;
  onUpgrade: () => void;
  onSave: (updatedUser: UserAPI) => void;
  setMessage: (
    value: React.SetStateAction<{
      type: 'success' | 'error';
      text: string;
    } | null>,
  ) => void;
}

const ProfileCard: React.FC<ProfileCardProps> = ({ user, onUpgrade, onSave, setMessage }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editedUser, setEditedUser] = useState<UserAPI>(user);
  const [formErrors, setFormErrors] = useState<{ [key: string]: string }>({});

  const handleEditToggle = () => {
    if (isEditing) {
      // Cancel editing, revert to original user data
      setEditedUser(user);
      setFormErrors({});
    }
    setIsEditing(!isEditing);
  };

  console.log(editedUser);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (isEditing) {
      const { name, value, type, checked } = e.target;
      setEditedUser((prev) => ({
        ...prev,
        [name]: type === 'checkbox' ? checked : value,
      }));
      // Clear error for the field being edited
      if (formErrors[name]) {
        setFormErrors((prev) => {
          const newErrors = { ...prev };
          delete newErrors[name];
          return newErrors;
        });
      }
    } else {
      setMessage({ type: 'error', text: 'Enable editing in the top right' });
      setTimeout(() => setMessage(null), 3000);
    }
  };

  const validateForm = () => {
    const errors: { [key: string]: string } = {};
    if (!editedUser.first_name.trim()) {
      errors.first_name = 'First name is required.';
    }
    if (!editedUser.last_name.trim()) {
      errors.last_name = 'Last name is required.';
    }
    if (!editedUser.email.trim()) {
      errors.email = 'Email is required.';
    } else if (!/\S+@\S+\.\S+/.test(editedUser.email)) {
      errors.email = 'Invalid email address.';
    }
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSave = () => {
    if (validateForm()) {
      onSave(editedUser);
      setIsEditing(false);
    }
  };

  return (
    <Card sx={{ mt: 3, p: 2 }}>
      <CardContent>
        <Box display="flex" justifyContent="space-between" alignItems="center">
          <Typography variant="h5" gutterBottom>
            Profile Information
          </Typography>
          {isEditing ? (
            <Box>
              <IconButton color="primary" onClick={handleSave}>
                <SaveIcon />
              </IconButton>
              <IconButton color="secondary" onClick={handleEditToggle}>
                <CancelIcon />
              </IconButton>
            </Box>
          ) : (
            <IconButton color="primary" onClick={handleEditToggle}>
              <EditIcon />
            </IconButton>
          )}
        </Box>
        <Grid container spacing={2}>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="First Name"
              name="first_name"
              value={editedUser.first_name}
              onChange={handleChange}
              error={!!formErrors.first_name}
              helperText={formErrors.first_name}
            />
          </Grid>
          <Grid size={{ xs: 12, sm: 6 }}>
            <TextField
              fullWidth
              label="Last Name"
              name="last_name"
              value={editedUser.last_name}
              onChange={handleChange}
              error={!!formErrors.last_name}
              helperText={formErrors.last_name}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <TextField
              fullWidth
              label="Email Address"
              name="email"
              type="email"
              value={editedUser.email}
              onChange={handleChange}
              error={!!formErrors.email}
              helperText={formErrors.email}
            />
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Typography variant="subtitle1">
              Subscription Tier: {user.tier === 'premium' ? 'Premium' : 'Basic'}
            </Typography>
            {user.tier === 'basic' && (
              <Button variant="contained" color="primary" onClick={onUpgrade} sx={{ mt: 1 }}>
                Upgrade to Premium
              </Button>
            )}
          </Grid>
          <Grid size={{ xs: 12 }}>
            <Typography variant="subtitle1">Notification Settings:</Typography>
            {/* Example Checkboxes - You'd manage these with state too */}
            <Box sx={{ display: 'flex', flexDirection: 'column' }}>
              <label>
                <input
                  type="checkbox"
                  name="productUpdateEmails"
                  checked={true} // Placeholder
                  onChange={() => {}} // Placeholder
                  disabled={!isEditing}
                />{' '}
                Product Update Emails
              </label>
              <label>
                <input
                  type="checkbox"
                  name="communicationEmails"
                  checked={true} // Placeholder
                  onChange={() => {}} // Placeholder
                  disabled={!isEditing}
                />{' '}
                Communication Emails
              </label>
            </Box>
          </Grid>
        </Grid>
        {Object.keys(formErrors).length > 0 && (
          <Alert severity="error" sx={{ mt: 2 }}>
            Please correct the errors in the form.
          </Alert>
        )}
      </CardContent>
    </Card>
  );
};

export default ProfileCard;
