'use client';

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  MenuItem,
  Box,
  Alert,
} from '@mui/material';
import { InviteMemberData } from '@/lib/api/families';

interface InviteMemberDialogProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: InviteMemberData) => Promise<void>;
  isLoading?: boolean;
}

export function InviteMemberDialog({
  open,
  onClose,
  onSubmit,
  isLoading = false,
}: InviteMemberDialogProps) {
  const [formData, setFormData] = useState<InviteMemberData>({
    email: '',
    role: 'viewer',
  });
  const [error, setError] = useState<string>('');

  useEffect(() => {
    if (open) {
      setFormData({
        email: '',
        role: 'viewer',
      });
      setError('');
    }
  }, [open]);

  const handleChange = (field: keyof InviteMemberData) => (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setFormData({ ...formData, [field]: e.target.value });
  };

  const handleSubmit = async () => {
    setError('');

    // Validation
    if (!formData.email.trim()) {
      setError('Please enter an email address');
      return;
    }

    // Basic email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      setError('Please enter a valid email address');
      return;
    }

    try {
      await onSubmit(formData);
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to invite member');
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
      aria-labelledby="invite-dialog-title"
      aria-describedby="invite-dialog-description"
    >
      <DialogTitle id="invite-dialog-title">Invite Family Member</DialogTitle>
      <DialogContent>
        <Box
          id="invite-dialog-description"
          sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}
        >
          {error && (
            <Alert severity="error" onClose={() => setError('')} role="alert">
              {error}
            </Alert>
          )}

          <TextField
            label="Email Address"
            type="email"
            value={formData.email}
            onChange={handleChange('email')}
            fullWidth
            required
            autoFocus
            disabled={isLoading}
            placeholder="member@example.com"
            helperText="Enter the email address of the person you want to invite"
          />

          <TextField
            label="Role"
            value={formData.role}
            onChange={handleChange('role')}
            fullWidth
            required
            select
            disabled={isLoading}
            helperText="Select the access level for this member"
          >
            <MenuItem value="parent">Parent - Full access to all features</MenuItem>
            <MenuItem value="caregiver">Caregiver - Can manage daily activities</MenuItem>
            <MenuItem value="viewer">Viewer - Can only view information</MenuItem>
          </TextField>
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={isLoading}>
          Cancel
        </Button>
        <Button onClick={handleSubmit} variant="contained" disabled={isLoading}>
          {isLoading ? 'Sending...' : 'Send Invitation'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
