"use client";

import { cn } from "@/lib/utils";
import { Input } from "../input";
import { Label } from "../label";
import { useId, useState, useEffect, useCallback } from "react";

// Popular email domains for autocomplete
const POPULAR_DOMAINS = [
  "gmail.com",
  "yahoo.com",
  "hotmail.com",
  "outlook.com",
  "icloud.com",
  "protonmail.com",
  "aol.com",
  "live.com",
];

interface EmailInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange"> {
  label?: string;
  containerProps?: React.ComponentProps<"div">;
  value: string;
  onChange: (value: string) => void;
  error?: string | null;
  suggestedEmail?: string | null;
  onSuggestionAccept?: (email: string) => void;
}

function EmailInput({
  className,
  label,
  containerProps,
  value,
  onChange,
  error,
  suggestedEmail,
  onSuggestionAccept,
  ...props
}: EmailInputProps) {
  const id = useId();
  const inputId = props.id || id;
  
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [showSuggestions, setShowSuggestions] = useState(false);

  // Generate domain suggestions based on input
  const generateSuggestions = useCallback((input: string): string[] => {
    if (!input || !input.includes("@")) return [];
    
    const [localPart, domainPart] = input.split("@");
    if (!localPart) return [];
    
    // If domain part is empty or partial, suggest completions
    if (!domainPart) {
      return POPULAR_DOMAINS.slice(0, 5).map(domain => `${localPart}@${domain}`);
    }
    
    // Filter domains that start with what user typed
    const matchingDomains = POPULAR_DOMAINS.filter(domain => 
      domain.toLowerCase().startsWith(domainPart.toLowerCase()) && domain !== domainPart
    );
    
    return matchingDomains.slice(0, 5).map(domain => `${localPart}@${domain}`);
  }, []);

  // Update suggestions when value changes
  useEffect(() => {
    const newSuggestions = generateSuggestions(value);
    setSuggestions(newSuggestions);
  }, [value, generateSuggestions]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    onChange(newValue);
    setShowSuggestions(true);
  };

  const handleSuggestionClick = (suggestion: string) => {
    onChange(suggestion);
    setShowSuggestions(false);
    setSuggestions([]);
  };

  const handleBlur = () => {
    // Delay to allow click on suggestion
    setTimeout(() => setShowSuggestions(false), 150);
  };

  const handleFocus = () => {
    if (suggestions.length > 0) {
      setShowSuggestions(true);
    }
  };

  const handleAcceptSuggestion = () => {
    if (suggestedEmail && onSuggestionAccept) {
      onSuggestionAccept(suggestedEmail);
    }
  };

  return (
    <div
      {...containerProps}
      className={cn("w-full flex flex-col gap-2 relative", containerProps?.className)}
    >
      {label && (
        <Label
          htmlFor={inputId}
          className="text-muted-foreground font-inter font-medium text-base"
        >
          {label}
        </Label>
      )}
      
      <div className="relative">
        <Input
          data-slot="email-input"
          type="email"
          autoComplete="email"
          className={cn(
            "py-3.5 px-4",
            "font-inter text-[18px]/[28px] font-semibold text-foreground",
            "placeholder:text-muted-foreground placeholder:text-[18px]/[28px] font-medium",
            "border-2 rounded-2xl",
            error ? "border-destructive" : "border-primary/30",
            className
          )}
          id={inputId}
          value={value}
          onChange={handleInputChange}
          onBlur={handleBlur}
          onFocus={handleFocus}
          aria-invalid={!!error}
          aria-errormessage={error || undefined}
          {...props}
        />

        {/* Autocomplete dropdown */}
        {showSuggestions && suggestions.length > 0 && (
          <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-xl shadow-lg overflow-hidden">
            {suggestions.map((suggestion) => (
              <button
                key={suggestion}
                type="button"
                className={cn(
                  "w-full px-4 py-2.5 text-left text-sm font-inter",
                  "hover:bg-primary/10 active:bg-primary/20 transition-colors"
                )}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => handleSuggestionClick(suggestion)}
              >
                <span className="text-muted-foreground">{suggestion.split("@")[0]}@</span>
                <span className="font-semibold text-foreground">{suggestion.split("@")[1]}</span>
              </button>
            ))}
          </div>
        )}
      </div>

      {/* Error message */}
      {error && (
        <div className="flex flex-col gap-2">
          <p className="text-destructive font-inter font-medium text-sm">
            {error}
          </p>
          
          {/* Suggestion button */}
          {suggestedEmail && onSuggestionAccept && (
            <button
              type="button"
              onClick={handleAcceptSuggestion}
              className={cn(
                "w-full py-2.5 px-4 rounded-xl",
                "bg-primary/10 hover:bg-primary/20 transition-colors",
                "text-sm font-inter font-medium text-primary",
                "flex items-center justify-center gap-2"
              )}
            >
              <span>Use</span>
              <span className="font-semibold">{suggestedEmail}</span>
              <span>instead?</span>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

export { EmailInput };
