import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  TextField,
  Button,
  Stepper,
  Step,
  StepLabel,
  Alert,
  CircularProgress,
  Box,
  Typography,
  FormControlLabel,
  Checkbox,
  InputAdornment,
  IconButton,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  ContentCopy,
} from '@mui/icons-material';
import { useForm } from 'react-hook-form';
import * as yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import api, { handleApiError } from '../../services/api';

interface CreateBucketDialogProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

interface FormData {
  bucketName: string;
  createUser: boolean;
  username: string;
  password: string;
}

const schema = yup.object({
  bucketName: yup
    .string()
    .required('Bucket name is required')
    .matches(
      /^[a-z0-9][a-z0-9.-]*[a-z0-9]$/,
      'Bucket name must be lowercase, 3-63 characters, start and end with letter/number'
    )
    .min(3, 'Minimum 3 characters')
    .max(63, 'Maximum 63 characters'),
  createUser: yup.boolean(),
  username: yup
    .string()
    .when('createUser', {
      is: true,
      then: (schema) =>
        schema
          .required('Username is required')
          .matches(
            /^[a-zA-Z0-9_-]+$/,
            'Username can only contain letters, numbers, hyphens, and underscores'
          )
          .min(3, 'Minimum 3 characters')
          .max(32, 'Maximum 32 characters'),
    }),
  password: yup
    .string()
    .when('createUser', {
      is: true,
      then: (schema) =>
        schema
          .required('Password is required')
          .min(8, 'Minimum 8 characters')
          .matches(
            /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/,
            'Password must contain uppercase, lowercase, and number'
          ),
    }),
});

const CreateBucketDialog: React.FC<CreateBucketDialogProps> = ({
  open,
  onClose,
  onSuccess,
}) => {
  const [activeStep, setActiveStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [success, setSuccess] = useState(false);
  const [credentials, setCredentials] = useState<{
    username: string;
    password: string;
  } | null>(null);

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
    reset,
  } = useForm<FormData>({
    resolver: yupResolver(schema),
    defaultValues: {
      createUser: true,
    },
  });

  const createUser = watch('createUser');

  const onSubmit = async (data: FormData) => {
    try {
      setLoading(true);
      setError('');

      if (data.createUser) {
        // Create bucket with user (like the script)
        await api.post('/buckets/with-user', {
          bucketName: data.bucketName,
          username: data.username,
          password: data.password,
        });
        setCredentials({
          username: data.username,
          password: data.password,
        });
      } else {
        // Create bucket only
        await api.post('/buckets', {
          bucketName: data.bucketName,
        });
      }

      setSuccess(true);
      setActiveStep(2);
    } catch (err) {
      setError(handleApiError(err));
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setActiveStep(0);
    setError('');
    setSuccess(false);
    setCredentials(null);
    reset();
    onClose();
  };

  const handleSuccess = () => {
    handleClose();
    onSuccess();
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  const steps = createUser
    ? ['Bucket Details', 'User Credentials', 'Complete']
    : ['Bucket Details', 'Complete'];

  return (
    <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>Create New Bucket</DialogTitle>
      <DialogContent>
        <Box sx={{ mt: 2 }}>
          <Stepper activeStep={activeStep} sx={{ mb: 3 }}>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>

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

          <form onSubmit={handleSubmit(onSubmit)}>
            {activeStep === 0 && (
              <>
                <TextField
                  {...register('bucketName')}
                  label="Bucket Name"
                  fullWidth
                  margin="normal"
                  error={!!errors.bucketName}
                  helperText={
                    errors.bucketName?.message || 'e.g., alice-bucket'
                  }
                  autoFocus
                />

                <FormControlLabel
                  control={
                    <Checkbox {...register('createUser')} defaultChecked />
                  }
                  label="Create user with full access to this bucket"
                  sx={{ mt: 2, mb: 2 }}
                />

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 3 }}>
                  <Button onClick={handleClose} sx={{ mr: 1 }}>
                    Cancel
                  </Button>
                  <Button
                    variant="contained"
                    onClick={() => setActiveStep(1)}
                    disabled={!!errors.bucketName}
                  >
                    Next
                  </Button>
                </Box>
              </>
            )}

            {activeStep === 1 && createUser && (
              <>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  Create a user with full access to the bucket. The user will be
                  able to read, write, and delete objects in this bucket.
                </Typography>

                <TextField
                  {...register('username')}
                  label="Username"
                  fullWidth
                  margin="normal"
                  error={!!errors.username}
                  helperText={errors.username?.message}
                  autoFocus
                />

                <TextField
                  {...register('password')}
                  label="Password"
                  type={showPassword ? 'text' : 'password'}
                  fullWidth
                  margin="normal"
                  error={!!errors.password}
                  helperText={
                    errors.password?.message ||
                    'Min 8 chars with uppercase, lowercase, and number'
                  }
                  InputProps={{
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          onClick={() => setShowPassword(!showPassword)}
                          edge="end"
                        >
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                />

                <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 3 }}>
                  <Button onClick={() => setActiveStep(0)}>Back</Button>
                  <Button
                    type="submit"
                    variant="contained"
                    disabled={loading}
                  >
                    {loading ? <CircularProgress size={24} /> : 'Create'}
                  </Button>
                </Box>
              </>
            )}

            {activeStep === 1 && !createUser && (
              <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 3 }}>
                <Button onClick={() => setActiveStep(0)}>Back</Button>
                <Button
                  type="submit"
                  variant="contained"
                  disabled={loading}
                >
                  {loading ? <CircularProgress size={24} /> : 'Create Bucket'}
                </Button>
              </Box>
            )}

            {activeStep === 2 && success && (
              <>
                <Alert severity="success" sx={{ mb: 2 }}>
                  Bucket created successfully!
                </Alert>

                {credentials && (
                  <Box sx={{ mt: 2 }}>
                    <Typography variant="h6" gutterBottom>
                      User Credentials
                    </Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                      Save these credentials securely. They won't be shown again.
                    </Typography>

                    <Box sx={{ bgcolor: 'grey.100', p: 2, borderRadius: 1, mb: 2 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                        <Typography variant="body2">
                          <strong>Username:</strong> {credentials.username}
                        </Typography>
                        <IconButton
                          size="small"
                          onClick={() => copyToClipboard(credentials.username)}
                        >
                          <ContentCopy fontSize="small" />
                        </IconButton>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2">
                          <strong>Password:</strong> {credentials.password}
                        </Typography>
                        <IconButton
                          size="small"
                          onClick={() => copyToClipboard(credentials.password)}
                        >
                          <ContentCopy fontSize="small" />
                        </IconButton>
                      </Box>
                    </Box>
                  </Box>
                )}

                <Box sx={{ display: 'flex', justifyContent: 'flex-end', mt: 3 }}>
                  <Button variant="contained" onClick={handleSuccess}>
                    Done
                  </Button>
                </Box>
              </>
            )}
          </form>
        </Box>
      </DialogContent>
    </Dialog>
  );
};

export default CreateBucketDialog;