'use client';

import { useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import Select, { StylesConfig, SingleValue } from 'react-select';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface Language {
  code: string;
  name: string;
  name_native: string;
  is_rtl: boolean;
  is_default: boolean;
  is_active: boolean;
}

// ✅ Simple attribute type - only what we need
interface Attribute {
  id: string;
  value: string; // Default language name
  is_active: boolean;
}

interface Translation {
  language_code: string;
  value: string;
}

interface OptionData {
  id?: string;
  attribute_id: string;
  is_active: boolean;
  translations: Translation[];
}

interface AttributeOptionFormProps {
  mode: 'create' | 'edit';
  initialData?: OptionData | null;
  languages: Language[];
  attributes: Attribute[]; // Simple attributes with default language only
}

interface SelectOption {
  value: string;
  label: string;
}

const INPUT_STYLE = {
  background: 'var(--color-surface-alt)',
  border: '1px solid var(--color-border)',
  color: 'var(--color-text)',
} as const;

const LABEL_STYLE = { color: 'var(--color-text-secondary)' } as const;
const ERROR_STYLE = { color: 'var(--color-danger)' } as const;

export default function AttributeOptionForm({ 
  mode, 
  initialData, 
  languages,
  attributes,
}: AttributeOptionFormProps) {
  const router = useRouter();
  const isEditing = mode === 'edit';

  // Get active languages, default first
  const activeLanguages = useMemo(() => {
    return languages
      .filter(l => l.is_active)
      .sort((a, b) => {
        if (a.is_default) return -1;
        if (b.is_default) return 1;
        return a.name.localeCompare(b.name);
      });
  }, [languages]);

  const isMultiLang = activeLanguages.length > 1;

  // Get default language
  const defaultLanguage = activeLanguages.find(l => l.is_default) || activeLanguages[0];

  // Initialize translations
  const initialTranslations = useMemo(() => {
    if (isEditing && initialData?.translations && initialData.translations.length > 0) {
      return initialData.translations;
    }
    return activeLanguages.map(lang => ({
      language_code: lang.code,
      value: '',
    }));
  }, [isEditing, initialData, activeLanguages]);

  // Build react-select options for attributes - ✅ Simple label only
  const attributeOptions: SelectOption[] = useMemo(() => {
    return attributes.map(attr => ({
      value: attr.id,
      label: attr.value || 'Unnamed Attribute',
    }));
  }, [attributes]);

  // Find currently selected attribute
  const selectedAttributeOption = useMemo(() => {
    if (!initialData?.attribute_id) return null;
    return attributeOptions.find(o => o.value === initialData.attribute_id) ?? null;
  }, [attributeOptions, initialData]);

  // State for active tab
  const [activeTab, setActiveTab] = useState<string>(defaultLanguage?.code || activeLanguages[0]?.code || 'en');

  // Form state
  const [formData, setFormData] = useState({
    attribute_id: initialData?.attribute_id || '',
    is_active: initialData?.is_active !== undefined ? initialData.is_active : true,
    translations: initialTranslations,
  });

  const [selectedAttribute, setSelectedAttribute] = useState<SingleValue<SelectOption>>(selectedAttributeOption);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Record<string, Record<string, string>>>({});

  // react-select custom styles
  const selectStyles: StylesConfig<SelectOption, false> = useMemo(() => ({
    control: (base, state) => ({
      ...base,
      background: 'var(--color-surface-alt)',
      border: `1px solid ${state.isFocused ? 'var(--color-cta)' : 'var(--color-border)'}`,
      borderRadius: '0.5rem',
      boxShadow: state.isFocused ? '0 0 0 2px color-mix(in srgb, var(--color-cta) 20%, transparent)' : 'none',
      minHeight: '42px',
      cursor: 'pointer',
      transition: 'all 0.15s',
      '&:hover': { borderColor: 'var(--color-cta)' },
    }),
    valueContainer: (base) => ({ ...base, padding: '2px 12px' }),
    singleValue: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
    placeholder: (base) => ({ ...base, color: 'var(--color-text-tertiary)', fontSize: '0.875rem' }),
    input: (base) => ({ ...base, color: 'var(--color-text)', fontSize: '0.875rem' }),
    menu: (base) => ({
      ...base,
      background: 'var(--color-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: '0.5rem',
      boxShadow: 'var(--shadow-card-md)',
      zIndex: 50,
      overflow: 'hidden',
    }),
    menuList: (base) => ({ ...base, padding: '4px' }),
    option: (base, state) => ({
      ...base,
      background: state.isSelected
        ? 'var(--color-cta)'
        : state.isFocused
        ? 'color-mix(in srgb, var(--color-cta) 10%, transparent)'
        : 'transparent',
      color: state.isSelected ? 'white' : 'var(--color-text)',
      fontSize: '0.875rem',
      borderRadius: '0.375rem',
      cursor: 'pointer',
      padding: '8px 12px',
      '&:active': { background: 'color-mix(in srgb, var(--color-cta) 20%, transparent)' },
    }),
    clearIndicator: (base) => ({
      ...base,
      color: 'var(--color-text-tertiary)',
      cursor: 'pointer',
      padding: '0 6px',
      '&:hover': { color: 'var(--color-danger)' },
    }),
    dropdownIndicator: (base) => ({
      ...base,
      color: 'var(--color-text-tertiary)',
      padding: '0 8px',
      '&:hover': { color: 'var(--color-text)' },
    }),
    indicatorSeparator: (base) => ({ ...base, background: 'var(--color-border)' }),
    noOptionsMessage: (base) => ({ ...base, color: 'var(--color-text-secondary)', fontSize: '0.875rem' }),
  }), []);

  const getTranslation = useCallback((languageCode: string) => {
    return formData.translations.find(t => t.language_code === languageCode);
  }, [formData.translations]);

  const updateTranslation = useCallback((languageCode: string, value: string) => {
    setFormData(prev => {
      const existingIndex = prev.translations.findIndex(t => t.language_code === languageCode);
      const newTranslations = [...prev.translations];
      
      if (existingIndex >= 0) {
        newTranslations[existingIndex] = { 
          ...newTranslations[existingIndex], 
          value: value 
        };
      } else {
        newTranslations.push({ 
          language_code: languageCode, 
          value: value 
        });
      }
      
      return { ...prev, translations: newTranslations };
    });
    
    // Clear error for this field
    if (errors[languageCode]?.value) {
      setErrors(prev => {
        const newErrors = { ...prev };
        if (newErrors[languageCode]) {
          delete newErrors[languageCode].value;
          if (Object.keys(newErrors[languageCode]).length === 0) {
            delete newErrors[languageCode];
          }
        }
        return newErrors;
      });
    }
  }, [errors]);

  const handleAttributeChange = useCallback((option: SingleValue<SelectOption>) => {
    setSelectedAttribute(option);
    setFormData(prev => ({ ...prev, attribute_id: option?.value ?? '' }));
    
    // Clear attribute error
    setErrors(prev => {
      const newErrors = { ...prev };
      delete newErrors['_general'];
      return newErrors;
    });
  }, []);

  const handleStatusChange = useCallback(() => {
    setFormData(prev => ({ ...prev, is_active: !prev.is_active }));
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setErrors({});
    setLoading(true);

    // Validate: attribute is selected
    if (!formData.attribute_id) {
      toast.error('Please select an attribute');
      setErrors(prev => ({
        ...prev,
        _general: { attribute: 'Attribute is required' }
      }));
      setLoading(false);
      return;
    }

    // Validate: at least one translation with value
    const hasValidTranslation = formData.translations.some(t => 
      t.value.trim().length > 0
    );
    if (!hasValidTranslation) {
      toast.error('At least one translation with value is required');
      setLoading(false);
      return;
    }

    try {
      const url = isEditing ? `/api/attribute-options/${initialData?.id}` : '/api/attribute-options';
      const method = isEditing ? 'PUT' : 'POST';

      const payload = {
        attribute_id: formData.attribute_id,
        is_active: formData.is_active,
        translations: formData.translations.filter(t => t.value.trim().length > 0),
      };

      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        if (data.errors) {
          const fieldErrors: Record<string, Record<string, string>> = {};
          if (Array.isArray(data.errors)) {
            data.errors.forEach((err: { path: string[]; message: string }) => {
              if (err.path) {
                const match = err.path.join('.');
                if (match.includes('translations')) {
                  const langMatch = match.match(/translations\[(\d+)\]/);
                  if (langMatch) {
                    const idx = parseInt(langMatch[1]);
                    const translation = formData.translations[idx];
                    if (translation) {
                      const field = err.path[err.path.length - 1];
                      if (!fieldErrors[translation.language_code]) {
                        fieldErrors[translation.language_code] = {};
                      }
                      fieldErrors[translation.language_code][field] = err.message;
                    }
                  }
                } else {
                  if (!fieldErrors['_general']) {
                    fieldErrors['_general'] = {};
                  }
                  fieldErrors['_general'][err.path.join('.')] = err.message;
                }
              }
            });
          }
          setErrors(fieldErrors);
          toast.error('Please fix the validation errors');
        } else {
          toast.error(getApiErrorMessage(data, 'Failed to save option'));
        }
        return;
      }

      toast.success(data.message || (isEditing ? 'Option updated successfully' : 'Option created successfully'));
      router.push('/admin/dashboard/attribute-options');
      router.refresh();
    } catch (err) {
      console.error('[AttributeOptionForm]', err);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  }

  // If no languages, show message
  if (activeLanguages.length === 0) {
    return (
      <div className="p-6 rounded-lg text-center" style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
      }}>
        <p style={{ color: 'var(--color-text-secondary)' }}>
          No active languages found. Please add languages first.
        </p>
      </div>
    );
  }

  // If no attributes, show message
  if (attributes.length === 0) {
    return (
      <div className="p-6 rounded-lg text-center" style={{
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
      }}>
        <p style={{ color: 'var(--color-text-secondary)' }}>
          No active attributes found. Please create an attribute first.
        </p>
      </div>
    );
  }

  return (
    <div className="p-6 md:p-8" style={{
      background: 'var(--color-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-card)',
      boxShadow: 'var(--shadow-card-md)',
      maxWidth: '1000px',
      width: '100%',
    }}>
      <form onSubmit={handleSubmit}>
        <div className="space-y-6">

          {/* Attribute Selection - ✅ Simple dropdown */}
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Attribute <span className="text-red-500">*</span>
            </label>
            <Select<SelectOption, false>
              instanceId="attribute-select"
              options={attributeOptions}
              value={selectedAttribute}
              onChange={handleAttributeChange}
              placeholder="Search or select attribute..."
              isSearchable
              styles={selectStyles}
              noOptionsMessage={() => 'No attributes found'}
            />
            {errors._general?.attribute && (
              <p className="text-xs mt-1" style={ERROR_STYLE}>{errors._general.attribute}</p>
            )}
            <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
              Select which attribute this option belongs to (e.g., Size, Color, Fabric)
            </p>
          </div>

          {/* Status Toggle */}
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Active Status
            </label>
            <button
              type="button"
              onClick={handleStatusChange}
              className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
              style={{
                background: formData.is_active ? 'var(--color-success)' : 'var(--color-surface-alt)',
                border: formData.is_active ? 'none' : '1px solid var(--color-border)',
                color: formData.is_active ? 'white' : 'var(--color-text-secondary)',
              }}
            >
              {formData.is_active ? '✅ Active' : '❌ Inactive'}
            </button>
          </div>

          {/* Language Tabs */}
          <div>
            {isMultiLang && (
              <div>
                <label className="block text-sm font-medium mb-3" style={LABEL_STYLE}>
                  Translations <span className="text-red-500">*</span>
                </label>

                <div className="flex flex-wrap gap-1 border-b" style={{ borderColor: 'var(--color-border)' }}>
                  {activeLanguages.map((lang) => {
                    const translation = getTranslation(lang.code);
                    const hasError = errors[lang.code]?.value;
                    const hasTranslation = translation?.value && translation.value.trim().length > 0;

                    return (
                      <button
                        key={lang.code}
                        type="button"
                        onClick={() => setActiveTab(lang.code)}
                        className={`px-4 py-2 text-sm font-medium transition-all whitespace-nowrap border-b-2 ${
                          activeTab === lang.code ? 'border-cta text-cta' : 'border-transparent text-text-secondary hover:text-text'
                        } ${hasError ? 'border-red-500' : ''}`}
                        style={{
                          color: activeTab === lang.code ? 'var(--color-cta)' : 'var(--color-text-secondary)',
                          borderColor: activeTab === lang.code ? 'var(--color-cta)' : 'transparent',
                          direction: lang.is_rtl ? 'rtl' : 'ltr',
                        }}
                      >
                        <span className="flex items-center gap-1">
                          {lang.is_default ? '⭐ ' : ''}
                          {lang.name_native}
                          <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>
                            ({lang.code})
                          </span>
                          {hasTranslation && <span className="text-xs text-green-500">✅</span>}
                          {hasError && <span className="text-red-500">*</span>}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Tab Content */}
            <div className="mt-4">
              {activeLanguages.map((lang) => {
                const isActive = activeTab === lang.code;
                const translation = getTranslation(lang.code);
                const isRTL = lang.is_rtl;
                const errorsForLang = errors[lang.code] || {};

                return (
                  <div key={lang.code} className={isActive ? 'block' : 'hidden'}>
                    <div className="space-y-4">

                      {/* Option Value */}
                      <div>
                        <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                          Option Value <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="text"
                          value={translation?.value || ''}
                          onChange={(e) => updateTranslation(lang.code, e.target.value)}
                          placeholder={isMultiLang ? `Enter option value in ${lang.name}` : 'Enter option value'}
                          className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errorsForLang.value ? 'border-red-500' : ''}`}
                          style={{ ...INPUT_STYLE, direction: isRTL ? 'rtl' : 'ltr' }}
                        />
                        {errorsForLang.value && (
                          <p className="text-xs mt-1" style={ERROR_STYLE}>{errorsForLang.value}</p>
                        )}
                        <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                          Examples: S, M, L, XL (for Size) | Red, Blue, Green (for Color) | Cotton, Polyester (for Fabric)
                        </p>
                      </div>

                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Form Actions */}
          <div className="flex gap-3 pt-4 border-t" style={{ borderColor: 'var(--color-border)' }}>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all disabled:opacity-50 hover:opacity-90"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"/>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                  </svg>
                  Saving...
                </span>
              ) : (isEditing ? 'Update Option' : 'Create Option')}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Cancel
            </button>
          </div>

        </div>
      </form>
    </div>
  );
}