import React, { useState, useEffect } from 'react';
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { X, Check, Loader2, AlertCircle } from 'lucide-react';
import { useToast } from '../../../context/ToastContext';

interface ChangeUsernameModalProps {
  onClose: () => void;
  currentUsername: string;
}

export const ChangeUsernameModal: React.FC<ChangeUsernameModalProps> = ({
  onClose,
  currentUsername,
}) => {
  const { addToast } = useToast();
  const [username, setUsername] = useState('');
  const [isChecking, setIsChecking] = useState(false);
  const [isAvailable, setIsAvailable] = useState<boolean | null>(null);

  // Debounced check
  useEffect(() => {
    if (!username || username === currentUsername) {
      setIsAvailable(null);
      return;
    }

    setIsChecking(true);
    const timer = setTimeout(() => {
      setIsChecking(false);
      // Mock logic: 'taken' is taken, otherwise available
      setIsAvailable(username.toLowerCase() !== 'taken');
    }, 500);

    return () => clearTimeout(timer);
  }, [username, currentUsername]);

  const handleConfirm = () => {
    if (isAvailable) {
      addToast('Username updated successfully', 'success');
      onClose();
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      <div
        className="absolute inset-0 bg-kodo-void/90 backdrop-blur-sm"
        onClick={onClose}
      ></div>
      <div className="relative w-full max-w-md bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl animate-scaleIn overflow-hidden">
        <div className="p-4 border-b border-kodo-steel bg-kodo-ink flex justify-between items-center">
          <h3 className="font-bold text-white">Change Username</h3>
          <button onClick={onClose}>
            <X className="w-5 h-5 text-gray-400 hover:text-white" />
          </button>
        </div>

        <div className="p-6 space-y-6">
          <div className="relative">
            <Input
              label="New Username"
              placeholder={currentUsername}
              value={username}
              onChange={(e) =>
                setUsername(e.target.value.replace(/[^a-zA-Z0-9_]/g, ''))
              }
              maxLength={20}
            />
            <div className="absolute right-4 top-[38px]">
              {isChecking && (
                <Loader2 className="w-4 h-4 animate-spin text-gray-400" />
              )}
              {!isChecking && isAvailable === true && (
                <Check className="w-4 h-4 text-kodo-lime" />
              )}
              {!isChecking && isAvailable === false && (
                <X className="w-4 h-4 text-kodo-red" />
              )}
            </div>

            {/* Feedback Text */}
            <div className="mt-2 text-xs h-4">
              {!isChecking && isAvailable === true && (
                <span className="text-kodo-lime">Username is available!</span>
              )}
              {!isChecking && isAvailable === false && (
                <span className="text-kodo-red">That username is taken.</span>
              )}
            </div>
          </div>

          <div className="bg-kodo-gold/10 border border-kodo-gold/30 p-3 rounded flex gap-3">
            <AlertCircle className="w-5 h-5 text-kodo-gold flex-shrink-0" />
            <div className="text-xs text-gray-300">
              <span className="font-bold text-kodo-gold block mb-1">
                Warning
              </span>
              Changing your username will change your profile URL. Your old
              username{' '}
              <span className="font-mono text-white">{currentUsername}</span>{' '}
              will become available for anyone else to claim.
            </div>
          </div>
        </div>

        <div className="p-4 border-t border-kodo-steel bg-kodo-ink flex justify-end gap-3">
          <Button variant="ghost" onClick={onClose}>
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleConfirm}
            disabled={!isAvailable}
          >
            Confirm Change
          </Button>
        </div>
      </div>
    </div>
  );
};
