// src/components/admin/menus/AddMenuItemModal.tsx

'use client';

import { useState, useCallback, useMemo } from 'react';
import { MenuItemModal } from './MenuItemModal';
import Select, { StylesConfig } from 'react-select';

interface Language {
  code: string;
  name: string;
  name_native: string;
  is_rtl: boolean;
  is_default: boolean;
  is_active: boolean;
}

interface ReferenceItem {
  id: string;
  title: string;
  name?: string;
  is_active: boolean;
  translations?: Array<{
    language_code: string;
    title?: string;
    name?: string;
  }>;
}

interface MenuItemTranslation {
  language_code: string;
  label: string;
  title_attr: string | null;
  description: string | null;
}

interface MenuItem {
  id: string;
  menu_id: string;
  parent_id: string | null;
  type: 'page' | 'category' | 'product' | 'custom' | 'post';
  reference_id: string | null;
  url: string | null;
  target: '_self' | '_blank';
  icon: string | null;
  css_class: string | null;
  display_type: 'default' | 'dropdown' | 'mega';
  mega_columns: number | null;
  mega_style: 'default' | 'cards' | 'grid' | 'list';
  is_active: boolean;
  translations: MenuItemTranslation[];
}

interface AddMenuItemModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: Omit<MenuItem, 'id' | 'children' | 'sort_order'>) => void;
  parentId: string | null;
  menuId: string;
  languages: Language[];
  pages: ReferenceItem[];
  categories: ReferenceItem[];
  posts: ReferenceItem[];
  products: ReferenceItem[];
  defaultLanguage: Language;
  initialData?: MenuItem | null;
  isEdit?: boolean;
}

interface SelectOption {
  value: string;
  label: string;
  data?: ReferenceItem;
}

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;

export function AddMenuItemModal({
  isOpen,
  onClose,
  onSave,
  parentId,
  menuId,
  languages,
  pages,
  categories,
  posts,
  products,
  initialData,
  isEdit = false,
}: AddMenuItemModalProps) {
  const isEditing = isEdit && initialData;
  const [isLoading, setIsLoading] = useState(false);

  // ── Form state ─────────────────────────────────────────────────────────────
  const [type, setType] = useState<MenuItem['type']>(initialData?.type || 'custom');
  const [referenceId, setReferenceId] = useState<string | null>(initialData?.reference_id || null);
  const [url, setUrl] = useState<string | null>(initialData?.url || null);
  const [target, setTarget] = useState<'_self' | '_blank'>(initialData?.target || '_self');
  const [icon, setIcon] = useState<string | null>(initialData?.icon || null);
  const [cssClass, setCssClass] = useState<string | null>(initialData?.css_class || null);
  const [displayType, setDisplayType] = useState<MenuItem['display_type']>(
    initialData?.display_type || 'default'
  );
  const [megaColumns, setMegaColumns] = useState<number | null>(initialData?.mega_columns || 3);
  const [megaStyle, setMegaStyle] = useState<MenuItem['mega_style']>(
    initialData?.mega_style || 'default'
  );
  const [isActive, setIsActive] = useState<boolean>(initialData?.is_active !== undefined ? initialData.is_active : true);

  // ── Translation state ─────────────────────────────────────────────────────
  const [translations, setTranslations] = useState<MenuItemTranslation[]>(
    initialData?.translations || languages.map((lang) => ({
      language_code: lang.code,
      label: '',
      title_attr: null,
      description: null,
    }))
  );

  // ── React-Select 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,
    }),
    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',
    }),
    noOptionsMessage: (base) => ({ ...base, color: 'var(--color-text-secondary)', fontSize: '0.875rem' }),
  }), []);

  // ── Reference options ─────────────────────────────────────────────────────
  const referenceOptions = useMemo(() => {
    if (type === 'page') {
      return pages.map((p) => ({
        value: p.id,
        label: p.title || 'Untitled',
        data: p,
      }));
    }
    if (type === 'category') {
      return categories.map((c) => ({
        value: c.id,
        label: c.name || c.title || 'Untitled',
        data: c,
      }));
    }
    if (type === 'post') {
      return posts.map((p) => ({
        value: p.id,
        label: p.title || 'Untitled',
        data: p,
      }));
    }
    if (type === 'product') {
      return products.map((p) => ({
        value: p.id,
        label: p.title || 'Untitled',
        data: p,
      }));
    }
    return [];
  }, [type, pages, categories, posts, products]);

  // ── Get translation for a language ──────────────────────────────────────
  const getTranslation = useCallback(
    (langCode: string) => {
      return translations.find((t) => t.language_code === langCode);
    },
    [translations]
  );

  // ── Update translation ───────────────────────────────────────────────────
  const updateTranslation = useCallback(
    (langCode: string, field: keyof MenuItemTranslation, value: string | null) => {
      setTranslations((prev) =>
        prev.map((t) =>
          t.language_code === langCode ? { ...t, [field]: value } : t
        )
      );
    },
    []
  );

  // ─── Auto-fill translations for ALL languages ──────────────────────────────
  const autoFillTranslations = useCallback((selectedType: MenuItem['type'], selectedId: string | null) => {
    if (!selectedId) return;

    let selectedItem: ReferenceItem | undefined;

    if (selectedType === 'page') {
      selectedItem = pages.find((p) => p.id === selectedId);
    } else if (selectedType === 'category') {
      selectedItem = categories.find((c) => c.id === selectedId);
    } else if (selectedType === 'post') {
      selectedItem = posts.find((p) => p.id === selectedId);
    } else if (selectedType === 'product') {
      selectedItem = products.find((p) => p.id === selectedId);
    }

    if (!selectedItem) return;

    if (selectedItem.translations && selectedItem.translations.length > 0) {
      const newTranslations = languages.map((lang) => {
        const existing = selectedItem.translations!.find(
          (t) => t.language_code === lang.code
        );
        const label = existing?.title || existing?.name || selectedItem.title || selectedItem.name || '';
        return {
          language_code: lang.code,
          label: label,
          title_attr: null,
          description: null,
        };
      });
      setTranslations(newTranslations);
    } else {
      const defaultTitle = selectedItem.title || selectedItem.name || '';
      const newTranslations = languages.map((lang) => ({
        language_code: lang.code,
        label: defaultTitle,
        title_attr: null,
        description: null,
      }));
      setTranslations(newTranslations);
    }
  }, [languages, pages, categories, posts, products]);

  // ─── Handle type change ──────────────────────────────────────────────────
  const handleTypeChange = useCallback((newType: MenuItem['type']) => {
    setType(newType);
    setReferenceId(null);
    setTranslations(
      languages.map((lang) => ({
        language_code: lang.code,
        label: '',
        title_attr: null,
        description: null,
      }))
    );
    if (newType === 'custom') {
      setUrl('/');
    } else {
      setUrl(null);
    }
  }, [languages]);

  // ─── Handle reference change ─────────────────────────────────────────────
  const handleReferenceChange = useCallback((option: SelectOption | null) => {
    setReferenceId(option?.value || null);
    if (option) {
      autoFillTranslations(type, option.value);
    } else {
      setTranslations(
        languages.map((lang) => ({
          language_code: lang.code,
          label: '',
          title_attr: null,
          description: null,
        }))
      );
    }
  }, [type, languages, autoFillTranslations]);

  // ─── Reset form to default/empty state ───────────────────────────────────
  const resetForm = useCallback(() => {
    setType('custom');
    setReferenceId(null);
    setUrl('/');
    setTarget('_self');
    setIcon(null);
    setCssClass(null);
    setDisplayType('default');
    setMegaColumns(3);
    setMegaStyle('default');
    setIsActive(true);
    setTranslations(
      languages.map((lang) => ({
        language_code: lang.code,
        label: '',
        title_attr: null,
        description: null,
      }))
    );
  }, [languages]);

  // ─── Handle close (backdrop click, cancel button, post-save) ────────────
  const handleClose = useCallback(() => {
    if (!isEditing) {
      resetForm();
    }
    setIsLoading(false);
    onClose();
  }, [isEditing, resetForm, onClose]);

  // ─── Handle save ──────────────────────────────────────────────────────────
  const handleSave = useCallback(async () => {
    const hasValidTranslation = translations.some((t) => t.label.trim().length > 0);
    if (!hasValidTranslation) {
      alert('Please provide a label in at least one language');
      return;
    }

    if ((type === 'page' || type === 'category' || type === 'post' || type === 'product') && !referenceId) {
      alert('Please select a page, category, post or product');
      return;
    }

    if (type === 'custom' && !url) {
      alert('Please enter a URL for custom link');
      return;
    }

    setIsLoading(true);
    try {
      await onSave({
        menu_id: menuId,
        parent_id: parentId,
        type,
        reference_id: referenceId,
        url,
        target,
        icon,
        css_class: cssClass,
        display_type: displayType,
        mega_columns: displayType === 'mega' ? megaColumns : null,
        mega_style: displayType === 'mega' ? megaStyle : 'default',
        is_active: isActive,
        translations: translations.filter((t) => t.label.trim().length > 0),
      });
      handleClose();
    } catch (error) {
      console.error('Failed to save menu item:', error);
      alert('Failed to save menu item. Please try again.');
    } finally {
      setIsLoading(false);
    }
  }, [
    translations,
    type,
    referenceId,
    url,
    target,
    icon,
    cssClass,
    displayType,
    megaColumns,
    megaStyle,
    isActive,
    parentId,
    menuId,
    onSave,
    handleClose,
  ]);

  // ─── Render ───────────────────────────────────────────────────────────────
  return (
    <MenuItemModal
      isOpen={isOpen}
      onClose={handleClose}
      onConfirm={handleSave}
      title={isEditing ? 'Edit Menu Item' : 'Add Menu Item'}
      confirmText={isEditing ? 'Update Item' : 'Add Item'}
      cancelText="Cancel"
      size="lg"
      isLoading={isLoading}
    >
      <div className="space-y-4">
        {/* Item Type */}
        <div>
          <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
            Item Type <span className="text-red-500">*</span>
          </label>
          <select
            value={type}
            onChange={(e) => handleTypeChange(e.target.value as MenuItem['type'])}
            className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
            style={INPUT_STYLE}
          >
            <option value="custom">Custom Link</option>
            <option value="page">Page</option>
            <option value="category">Category</option>
            <option value="post">Post</option>
            <option value="product">Product</option>
          </select>
        </div>

        {/* Reference */}
        {(type === 'page' || type === 'category' || type === 'post' || type === 'product') && (
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Select {type.charAt(0).toUpperCase() + type.slice(1)} <span className="text-red-500">*</span>
            </label>
            <Select<SelectOption, false>
              instanceId="menu-reference-select"
              options={referenceOptions}
              value={referenceOptions.find((o) => o.value === referenceId) || null}
              onChange={handleReferenceChange}
              placeholder={`Search ${type}...`}
              isSearchable
              styles={selectStyles}
              noOptionsMessage={() => `No ${type}s found`}
            />
            <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
              💡 Translations will auto-fill from the selected {type} in each language
            </p>
          </div>
        )}

        {/* Custom URL */}
        {type === 'custom' && (
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              URL <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={url || ''}
              onChange={(e) => setUrl(e.target.value || null)}
              placeholder="e.g., /about-us, https://example.com"
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
              style={INPUT_STYLE}
            />
          </div>
        )}

        {/* Target */}
        <div>
          <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
            Open In
          </label>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setTarget('_self')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                target === '_self'
                  ? 'ring-2 ring-cta'
                  : 'border'
              }`}
              style={{
                background: target === '_self' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                color: target === '_self' ? 'white' : 'var(--color-text-secondary)',
                border: target === '_self' ? 'none' : '1px solid var(--color-border)',
              }}
            >
              Same Window
            </button>
            <button
              type="button"
              onClick={() => setTarget('_blank')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                target === '_blank'
                  ? 'ring-2 ring-cta'
                  : 'border'
              }`}
              style={{
                background: target === '_blank' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                color: target === '_blank' ? 'white' : 'var(--color-text-secondary)',
                border: target === '_blank' ? 'none' : '1px solid var(--color-border)',
              }}
            >
              New Window
            </button>
          </div>
        </div>

        {/* Display Type */}
        <div>
          <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
            Display Type
          </label>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
            <button
              type="button"
              onClick={() => setDisplayType('default')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                displayType === 'default'
                  ? 'ring-2 ring-cta'
                  : 'border'
              }`}
              style={{
                background: displayType === 'default' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                color: displayType === 'default' ? 'white' : 'var(--color-text-secondary)',
                border: displayType === 'default' ? 'none' : '1px solid var(--color-border)',
              }}
            >
              Default
            </button>
            <button
              type="button"
              onClick={() => setDisplayType('dropdown')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                displayType === 'dropdown'
                  ? 'ring-2 ring-cta'
                  : 'border'
              }`}
              style={{
                background: displayType === 'dropdown' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                color: displayType === 'dropdown' ? 'white' : 'var(--color-text-secondary)',
                border: displayType === 'dropdown' ? 'none' : '1px solid var(--color-border)',
              }}
            >
              Dropdown
            </button>
            <button
              type="button"
              onClick={() => setDisplayType('mega')}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                displayType === 'mega'
                  ? 'ring-2 ring-cta'
                  : 'border'
              }`}
              style={{
                background: displayType === 'mega' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
                color: displayType === 'mega' ? 'white' : 'var(--color-text-secondary)',
                border: displayType === 'mega' ? 'none' : '1px solid var(--color-border)',
              }}
            >
              Mega Menu
            </button>
          </div>
        </div>

        {/* Mega Menu Options */}
        {displayType === 'mega' && (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 p-4 rounded-lg" style={{ background: 'var(--color-surface-alt)' }}>
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Columns
              </label>
              <select
                value={megaColumns || 3}
                onChange={(e) => setMegaColumns(parseInt(e.target.value))}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={INPUT_STYLE}
              >
                <option value={2}>2 Columns</option>
                <option value={3}>3 Columns</option>
                <option value={4}>4 Columns</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
                Style
              </label>
              <select
                value={megaStyle}
                onChange={(e) => setMegaStyle(e.target.value as MenuItem['mega_style'])}
                className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                style={INPUT_STYLE}
              >
                <option value="default">Default</option>
                <option value="cards">Cards</option>
                <option value="grid">Grid</option>
                <option value="list">List</option>
              </select>
            </div>
          </div>
        )}

        {/* Icon & CSS Class */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              Icon (CSS class)
            </label>
            <input
              type="text"
              value={icon || ''}
              onChange={(e) => setIcon(e.target.value || null)}
              placeholder="e.g., fa-home, bi-house"
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
              style={INPUT_STYLE}
            />
          </div>
          <div>
            <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
              CSS Class
            </label>
            <input
              type="text"
              value={cssClass || ''}
              onChange={(e) => setCssClass(e.target.value || null)}
              placeholder="e.g., custom-class"
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
              style={INPUT_STYLE}
            />
          </div>
        </div>

        {/* Status */}
        <div>
          <label className="block text-sm font-medium mb-1.5" style={LABEL_STYLE}>
            Status
          </label>
          <button
            type="button"
            onClick={() => setIsActive(!isActive)}
            className="px-4 py-2 rounded-lg text-sm font-medium transition-all"
            style={{
              background: isActive ? 'var(--color-success)' : 'var(--color-surface-alt)',
              border: isActive ? 'none' : '1px solid var(--color-border)',
              color: isActive ? 'white' : 'var(--color-text-secondary)',
            }}
          >
            {isActive ? '✅ Active' : '❌ Inactive'}
          </button>
        </div>

        {/* Translations */}
        <div>
          <label className="block text-sm font-medium mb-3" style={LABEL_STYLE}>
            Translations <span className="text-red-500">*</span>
          </label>
          <div className="space-y-3 max-h-75 overflow-y-auto">
            {languages.map((lang) => {
              const trans = getTranslation(lang.code);
              const isDefault = lang.is_default;
              const isRTL = lang.is_rtl;

              return (
                <div
                  key={lang.code}
                  className="p-3 rounded-lg"
                  style={{
                    background: 'var(--color-surface-alt)',
                    border: '1px solid var(--color-border)',
                  }}
                >
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-sm font-medium">
                      {isDefault ? '⭐ ' : ''}
                      {lang.name_native} ({lang.code})
                    </span>
                  </div>
                  <div className="space-y-2">
                    <input
                      type="text"
                      value={trans?.label || ''}
                      onChange={(e) => updateTranslation(lang.code, 'label', e.target.value)}
                      placeholder={`Enter label in ${lang.name}`}
                      className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                      style={{
                        ...INPUT_STYLE,
                        direction: isRTL ? 'rtl' : 'ltr',
                      }}
                    />
                    <input
                      type="text"
                      value={trans?.title_attr || ''}
                      onChange={(e) => updateTranslation(lang.code, 'title_attr', e.target.value || null)}
                      placeholder="Title attribute (SEO tooltip)"
                      className="w-full px-3 py-2 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20"
                      style={{
                        ...INPUT_STYLE,
                        direction: isRTL ? 'rtl' : 'ltr',
                      }}
                    />
                  </div>
                </div>
              );
            })}
          </div>
          <p className="text-xs mt-2" style={{ color: 'var(--color-text-tertiary)' }}>
            💡 Select a page, category, post or product above to auto-fill translations for all languages
          </p>
        </div>
      </div>
    </MenuItemModal>
  );
}