import * as React from "react";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { TermTooltip } from "@/components/ui/term-tooltip";
import { fieldHints } from "@/lib/enhancedValidation";
import { cn } from "@/lib/utils";
import { CheckCircle2, AlertCircle } from "lucide-react";

/**
 * Field types that automatically get hints and terminology support
 */
export type FormFieldType = 
  | 'text' 
  | 'number' 
  | 'url' 
  | 'email' 
  | 'phone'
  | 'textarea'
  | 'slug'
  | 'height-requirement'
  | 'age-requirement'
  | 'capacity'
  | 'duration'
  | 'speed'
  | 'height'
  | 'length'
  | 'inversions'
  | 'g-force'
  | 'source-url'
  | 'submission-notes';

interface FormFieldWrapperProps {
  /** Field identifier */
  id: string;
  
  /** Field label text */
  label: string;
  
  /** Field type - determines automatic hints and validation */
  fieldType?: FormFieldType;
  
  /** Terminology key for tooltip (e.g., 'lsm', 'rmc') */
  termKey?: string;
  
  /** Show tooltip icon on label */
  showTermIcon?: boolean;
  
  /** Whether field is required */
  required?: boolean;
  
  /** Whether field is optional (shows badge) */
  optional?: boolean;
  
  /** Custom hint text (overrides automatic hint) */
  hint?: string;
  
  /** Error message from validation (pass errors.field?.message) */
  error?: string;
  
  /** Current value for character counting */
  value?: string | number;
  
  /** Maximum length for character counting */
  maxLength?: number;
  
  /** Input props to pass through */
  inputProps?: React.ComponentProps<typeof Input>;
  
  /** Textarea props to pass through (when fieldType is 'textarea') */
  textareaProps?: React.ComponentProps<typeof Textarea>;
  
  /** Additional className for wrapper */
  className?: string;
  
  /** Hide automatic hint */
  hideHint?: boolean;
  
  /** When to show validation feedback */
  validationMode?: 'realtime' | 'onBlur';
  
  /** Callback when field is blurred (for onBlur mode) */
  onBlur?: () => void;
}

/**
 * Get automatic hint based on field type
 */
function getAutoHint(fieldType?: FormFieldType): string | undefined {
  if (!fieldType) return undefined;
  
  const hintMap: Record<FormFieldType, string | undefined> = {
    'text': undefined,
    'number': undefined,
    'url': fieldHints.websiteUrl,
    'email': fieldHints.email,
    'phone': fieldHints.phone,
    'textarea': undefined,
    'slug': fieldHints.slug,
    'height-requirement': fieldHints.heightRequirement,
    'age-requirement': fieldHints.ageRequirement,
    'capacity': fieldHints.capacity,
    'duration': fieldHints.duration,
    'speed': fieldHints.speed,
    'height': fieldHints.height,
    'length': fieldHints.length,
    'inversions': fieldHints.inversions,
    'g-force': fieldHints.gForce,
    'source-url': fieldHints.sourceUrl,
    'submission-notes': fieldHints.submissionNotes,
  };
  
  return hintMap[fieldType];
}

/**
 * Get input type from field type
 */
function getInputType(fieldType?: FormFieldType): string {
  if (!fieldType) return 'text';
  
  const typeMap: Record<FormFieldType, string> = {
    'text': 'text',
    'number': 'number',
    'url': 'url',
    'email': 'email',
    'phone': 'tel',
    'textarea': 'text',
    'slug': 'text',
    'height-requirement': 'number',
    'age-requirement': 'number',
    'capacity': 'number',
    'duration': 'number',
    'speed': 'number',
    'height': 'number',
    'length': 'number',
    'inversions': 'number',
    'g-force': 'number',
    'source-url': 'url',
    'submission-notes': 'text',
  };
  
  return typeMap[fieldType] || 'text';
}

/**
 * Unified form field wrapper with automatic hints, validation, and terminology
 * 
 * @example
 * ```tsx
 * <FormFieldWrapper
 *   id="website_url"
 *   label="Website URL"
 *   fieldType="url"
 *   error={errors.website_url?.message}
 *   inputProps={{...register('website_url'), placeholder: "https://..."}}
 * />
 * ```
 * 
 * @example With terminology tooltip
 * ```tsx
 * <FormFieldWrapper
 *   id="propulsion"
 *   label="Propulsion Method"
 *   fieldType="text"
 *   termKey="lsm"
 *   hint="Common: LSM Launch, Chain Lift, Hydraulic Launch"
 *   inputProps={{...register('propulsion')}}
 * />
 * ```
 * 
 * @example Textarea with character count
 * ```tsx
 * <FormFieldWrapper
 *   id="notes"
 *   label="Notes"
 *   fieldType="submission-notes"
 *   optional
 *   value={watch('notes')}
 *   maxLength={1000}
 *   textareaProps={{...register('notes'), rows: 3}}
 * />
 * ```
 */
export function FormFieldWrapper({
  id,
  label,
  fieldType,
  termKey,
  showTermIcon = true,
  required = false,
  optional = false,
  hint,
  error,
  value,
  maxLength,
  inputProps,
  textareaProps,
  className,
  hideHint = false,
  validationMode = 'realtime',
  onBlur,
}: FormFieldWrapperProps) {
  const [hasBlurred, setHasBlurred] = React.useState(false);
  const isTextarea = fieldType === 'textarea' || fieldType === 'submission-notes';
  const autoHint = getAutoHint(fieldType);
  const displayHint = hint || autoHint;
  const inputType = getInputType(fieldType);
  
  // Character count for textareas with maxLength
  const showCharCount = isTextarea && maxLength && typeof value === 'string';
  const charCount = typeof value === 'string' ? value.length : 0;
  
  // Determine validation state
  const shouldShowValidation = validationMode === 'realtime' || (validationMode === 'onBlur' && hasBlurred);
  const hasValue = value !== undefined && value !== null && value !== '';
  const isValid = shouldShowValidation && !error && hasValue;
  const hasError = shouldShowValidation && !!error;
  
  // Blur handler
  const handleBlur = (e: React.FocusEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setHasBlurred(true);
    if (validationMode === 'onBlur' && onBlur) {
      onBlur();
    }
    // Call original onBlur if provided
    if ('value' in e.target && textareaProps?.onBlur) {
      textareaProps.onBlur(e as React.FocusEvent<HTMLTextAreaElement>);
    } else if (inputProps?.onBlur) {
      inputProps.onBlur(e as React.FocusEvent<HTMLInputElement>);
    }
  };
  
  return (
    <div className={cn("space-y-2", className)} data-error={hasError ? "true" : undefined}>
      {/* Label with optional terminology tooltip */}
      <Label htmlFor={id} className="flex items-center gap-2">
        {termKey ? (
          <TermTooltip term={termKey} showIcon={showTermIcon}>
            {label}
          </TermTooltip>
        ) : (
          label
        )}
        {required && <span className="text-destructive">*</span>}
        {optional && (
          <span className="text-xs text-muted-foreground font-normal">
            (Optional)
          </span>
        )}
      </Label>
      
      {/* Input or Textarea with validation icons */}
      <div className="relative">
        {isTextarea ? (
          <Textarea
            id={id}
            className={cn(
              "pr-10 transition-all duration-300 ease-in-out",
              "focus:ring-2 focus:ring-primary/20 focus:border-primary",
              error && "border-destructive focus:ring-destructive/20",
              isValid && "border-green-500/50 focus:ring-green-500/20"
            )}
            maxLength={maxLength}
            onBlur={handleBlur}
            {...textareaProps}
          />
        ) : (
          <Input
            id={id}
            type={inputType}
            className={cn(
              "pr-10 transition-all duration-300 ease-in-out",
              "focus:ring-2 focus:ring-primary/20 focus:border-primary",
              error && "border-destructive focus:ring-destructive/20",
              isValid && "border-green-500/50 focus:ring-green-500/20"
            )}
            maxLength={maxLength}
            onBlur={handleBlur}
            {...inputProps}
          />
        )}
        
        {/* Validation icon with animation */}
        {(isValid || hasError) && (
          <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
            {isValid && (
              <CheckCircle2 className="h-4 w-4 text-green-500 animate-fade-in" />
            )}
            {hasError && (
              <AlertCircle className="h-4 w-4 text-destructive animate-fade-in" />
            )}
          </div>
        )}
      </div>
      
      {/* Hint text (if not hidden and exists) */}
      {!hideHint && displayHint && !error && (
        <p className="text-xs text-muted-foreground animate-slide-in-down">
          {displayHint}
          {showCharCount && ` (${charCount}/${maxLength} characters)`}
        </p>
      )}
      
      {/* Character count only (when no hint) */}
      {!hideHint && !displayHint && showCharCount && !error && (
        <p className="text-xs text-muted-foreground">
          {charCount}/{maxLength} characters
        </p>
      )}
      
      {/* Error message with animation */}
      {error && (
        <p className="text-sm text-destructive animate-slide-in-down">
          {error}
          {showCharCount && ` (${charCount}/${maxLength})`}
        </p>
      )}
    </div>
  );
}

/**
 * Preset configurations for common field types
 */
export const formFieldPresets = {
  websiteUrl: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'url' as FormFieldType,
    label: 'Website URL',
    validationMode: 'onBlur',
    ...props,
  }),
  
  email: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'email' as FormFieldType,
    label: 'Email',
    ...props,
  }),
  
  phone: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'phone' as FormFieldType,
    label: 'Phone Number',
    ...props,
  }),
  
  sourceUrl: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'source-url' as FormFieldType,
    label: 'Source URL',
    optional: true,
    ...props,
  }),
  
  submissionNotes: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'submission-notes' as FormFieldType,
    label: 'Notes for Reviewers',
    optional: true,
    maxLength: 1000,
    ...props,
  }),
  
  heightRequirement: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'height-requirement' as FormFieldType,
    label: 'Height Requirement',
    ...props,
  }),
  
  capacity: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'capacity' as FormFieldType,
    label: 'Capacity per Hour',
    ...props,
  }),
  
  duration: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'duration' as FormFieldType,
    label: 'Duration (seconds)',
    ...props,
  }),
  
  speed: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'speed' as FormFieldType,
    label: 'Max Speed',
    termKey: 'kilometers-per-hour',
    ...props,
  }),
  
  height: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'height' as FormFieldType,
    label: 'Max Height',
    termKey: 'meters',
    ...props,
  }),
  
  length: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'length' as FormFieldType,
    label: 'Track Length',
    termKey: 'meters',
    ...props,
  }),
  
  inversions: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'inversions' as FormFieldType,
    label: 'Inversions',
    termKey: 'inversion',
    ...props,
  }),
  
  gForce: (props: Partial<FormFieldWrapperProps>) => ({
    fieldType: 'g-force' as FormFieldType,
    label: 'Max G-Force',
    termKey: 'g-force',
    ...props,
  }),
};
