'use client';

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

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

export function JoinFamilyDialog({
  open,
  onClose,
  onSubmit,
  isLoading = false,
}: JoinFamilyDialogProps) {
  const [shareCode, setShareCode] = useState<string>('');
  const [error, setError] = useState<string>('');

  useEffect(() => {
    if (open) {
      setShareCode('');
      setError('');
    }
  }, [open]);

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

    // Validation
    if (!shareCode.trim()) {
      setError('Please enter a share code');
      return;
    }

    try {
      await onSubmit({ shareCode: shareCode.trim() });
      onClose();
    } catch (err: any) {
      setError(err.message || 'Failed to join family');
    }
  };

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

          <Typography variant="body2" color="text.secondary" id="join-family-dialog-description">
            Enter the share code provided by the family administrator to join their family.
          </Typography>

          <TextField
            label="Share Code"
            value={shareCode}
            onChange={(e) => setShareCode(e.target.value)}
            fullWidth
            required
            autoFocus
            disabled={isLoading}
            placeholder="Enter family share code"
            helperText="Ask a family member for their share code"
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={isLoading}>
          Cancel
        </Button>
        <Button onClick={handleSubmit} variant="contained" disabled={isLoading}>
          {isLoading ? 'Joining...' : 'Join Family'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}
