import { useState } from 'react';
import { Modal } from '@/components/ui/Modal';
import { Input } from '@/components/ui/Input';
import { Select } from '@/components/ui/Select';
import { Button } from '@/components/ui/Button';
import { useToast } from '@/components/ui/Toast';
import { adminAPI } from '@/api/client';

interface BanDialogProps {
  open: boolean;
  onClose: () => void;
  userId: string;
  username: string;
  onBanned?: () => void;
}

export default function BanDialog({ open, onClose, userId, username, onBanned }: BanDialogProps) {
  const { toast } = useToast();
  const [banType, setBanType] = useState('temp');
  const [duration, setDuration] = useState('24h');
  const [reason, setReason] = useState('');
  const [loading, setLoading] = useState(false);

  async function handleBan() {
    if (!reason.trim()) return;
    setLoading(true);
    try {
      await adminAPI.banUser(userId, {
        type: banType,
        reason,
        duration: banType === 'temp' ? duration : undefined,
      });
      toast(`${username} has been banned`, 'success');
      onBanned?.();
      onClose();
    } catch {
      toast('Failed to issue ban', 'error');
    } finally {
      setLoading(false);
    }
  }

  return (
    <Modal open={open} onClose={onClose} title={`Ban ${username}`}>
      <div className="space-y-4">
        <Select
          label="Ban Type"
          value={banType}
          onChange={setBanType}
          options={[
            { value: 'warning', label: 'Warning (no restriction)' },
            { value: 'temp', label: 'Temporary Ban' },
            { value: 'perm', label: 'Permanent Ban' },
            { value: 'game', label: 'Game Ban (queue only)' },
            { value: 'full', label: 'Full Ban (cannot login)' },
          ]}
        />
        {banType === 'temp' && (
          <Select
            label="Duration"
            value={duration}
            onChange={setDuration}
            options={[
              { value: '1h', label: '1 Hour' },
              { value: '6h', label: '6 Hours' },
              { value: '24h', label: '24 Hours' },
              { value: '3d', label: '3 Days' },
              { value: '7d', label: '7 Days' },
              { value: '30d', label: '30 Days' },
            ]}
          />
        )}
        <Input label="Reason (shown to user)" value={reason} onChange={(e) => setReason(e.target.value)} />
        <div className="flex justify-end gap-3 pt-2">
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button variant="danger" onClick={handleBan} loading={loading} disabled={!reason.trim()}>
            Confirm Ban
          </Button>
        </div>
      </div>
    </Modal>
  );
}
