'use client';

import React, { useState } from 'react';
import Image from 'next/image';
import { ProfileSection } from '@/services/profile-sections.service';
import DynamicField from './DynamicField';

// Error boundary to catch rendering errors in repeatable sections
class RepeatableSectionErrorBoundary extends React.Component<
  { sectionName: string; children: React.ReactNode },
  { hasError: boolean }
> {
  constructor(props: { sectionName: string; children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error(`Error rendering repeatable section "${this.props.sectionName}":`, error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="bg-white rounded-[20px] p-6 shadow-[0px_10px_20px_rgba(217,217,217,0.5)]">
          <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
            <p className="text-sm text-red-600">
              Failed to load section: {this.props.sectionName}
            </p>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

// Map section slugs to icon paths
const sectionIcons: Record<string, string> = {
  'basic-information': '/assets/icons/basic-information-icon.svg',
  'contact-information': '/assets/icons/email-orange-icon.svg',
  'location': '/assets/icons/location-orange-icon.svg',
  'professional-info': '/assets/icons/certification-icon.svg',
  'specialization': '/assets/icons/home-icon.svg',
  'experience': '/assets/icons/star-icon.svg',
  'availability': '/assets/icons/availability-clock-icon.svg',
  'biography': '/assets/icons/bio-icon.svg',
  'attached-documents': '/assets/icons/attachment-icon.svg',
  'hobbies': '/assets/icons/heart-icon.svg',
  'testimonials': '/assets/icons/quote-icon.svg',
  'certification': '/assets/icons/certification-icon.svg',
};

// Map icon names (from database) to icon paths
const iconNameToPath: Record<string, string> = {
  'star': '/assets/icons/star-icon.svg',
  'home': '/assets/icons/home-icon.svg',
  'location': '/assets/icons/location-orange-icon.svg',
  'heart': '/assets/icons/heart-icon.svg',
  'clock': '/assets/icons/availability-clock-icon.svg',
  'user': '/assets/icons/basic-information-icon.svg',
  'email': '/assets/icons/email-orange-icon.svg',
  'phone': '/assets/icons/phone-orange-icon.svg',
  'document': '/assets/icons/attachment-icon.svg',
  'certificate': '/assets/icons/certification-icon.svg',
  'certification': '/assets/icons/certification-icon.svg',
  'quote': '/assets/icons/quote-icon.svg',
  'bio': '/assets/icons/bio-icon.svg',
  'professional': '/assets/icons/professional-icon.svg',
  'wallet': '/assets/icons/wallet-icon.svg',
  'chart': '/assets/icons/chart-icon.svg',
  'dollar': '/assets/icons/dollar-icon.svg',
  'calendar': '/assets/icons/calendar-icon.svg',
};

// Default icon for sections without a specific icon
const defaultIcon = '/assets/icons/professional-icon.svg';

// Helper to check if a string is an emoji
const isEmojiString = (str: string): boolean => {
  const emojiRegex = /^[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F600}-\u{1F64F}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]/u;
  return emojiRegex.test(str);
};

// Type for a single entry's data
export type RepeatableEntryData = Record<string, unknown>;

interface RepeatableSectionProps {
  section: ProfileSection;
  entries: RepeatableEntryData[];
  onChange: (sectionSlug: string, entries: RepeatableEntryData[]) => void;
  errors?: Record<string, Record<string, string>>; // errors[entryIndex][fieldSlug]
}

export default function RepeatableSection({
  section,
  entries,
  onChange,
  errors,
}: RepeatableSectionProps) {
  const [expandedEntries, setExpandedEntries] = useState<Set<number>>(new Set([0]));

  // Determine icon source
  let iconPath: string = defaultIcon;
  let isEmoji = false;

  if (section.icon) {
    if (section.icon.startsWith('/') || section.icon.startsWith('http')) {
      iconPath = section.icon;
    } else if (isEmojiString(section.icon)) {
      isEmoji = true;
    } else if (iconNameToPath[section.icon.toLowerCase()]) {
      iconPath = iconNameToPath[section.icon.toLowerCase()];
    } else {
      iconPath = sectionIcons[section.slug] || defaultIcon;
    }
  } else {
    iconPath = sectionIcons[section.slug] || defaultIcon;
  }

  // Sort fields by sortOrder and filter active, non-search-only fields - safely handle missing/null fields
  const fields = Array.isArray(section.fields) ? section.fields : [];
  const sortedFields = [...fields].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0));
  const activeFields = sortedFields.filter(f => f.isActive && !f.isSearchableOnly);

  if (activeFields.length === 0) {
    return null;
  }

  // Ensure at least one empty entry exists
  const displayEntries = entries.length > 0 ? entries : [{}];

  const handleAddEntry = () => {
    const newEntries = [...displayEntries, {}];
    onChange(section.slug, newEntries);
    // Expand the new entry
    setExpandedEntries(prev => new Set([...prev, newEntries.length - 1]));
  };

  const handleRemoveEntry = (index: number) => {
    if (displayEntries.length <= 1) return; // Keep at least one entry
    const newEntries = displayEntries.filter((_, i) => i !== index);
    onChange(section.slug, newEntries);
    // Update expanded entries
    setExpandedEntries(prev => {
      const newSet = new Set<number>();
      prev.forEach(i => {
        if (i < index) newSet.add(i);
        else if (i > index) newSet.add(i - 1);
      });
      return newSet;
    });
  };

  const handleFieldChange = (entryIndex: number, fieldSlug: string, value: unknown) => {
    const newEntries = [...displayEntries];
    newEntries[entryIndex] = {
      ...newEntries[entryIndex],
      [fieldSlug]: value,
    };
    onChange(section.slug, newEntries);
  };

  const toggleExpand = (index: number) => {
    setExpandedEntries(prev => {
      const newSet = new Set(prev);
      if (newSet.has(index)) {
        newSet.delete(index);
      } else {
        newSet.add(index);
      }
      return newSet;
    });
  };

  const getEntryTitle = (entry: RepeatableEntryData, index: number): string => {
    // Try to get a meaningful title from the first text field
    for (const field of activeFields) {
      if (field.fieldType === 'TEXT' && entry[field.slug]) {
        return String(entry[field.slug]);
      }
    }
    return `${section.name} ${index + 1}`;
  };

  const sectionName = section.name || 'Section';

  return (
    <RepeatableSectionErrorBoundary sectionName={sectionName}>
    <div
      id={section.slug}
      className="bg-white rounded-[20px] p-6 shadow-[0px_10px_20px_rgba(217,217,217,0.5)] scroll-mt-[100px]"
    >
      {/* Section Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="w-[40px] h-[40px] flex items-center justify-center">
            {isEmoji ? (
              <span className="text-2xl">{section.icon}</span>
            ) : (
              <Image
                src={iconPath}
                alt={sectionName}
                width={24}
                height={24}
                className="object-contain"
              />
            )}
          </div>
          <div>
            <h2 className="text-[18px] font-bold font-serif text-[#00293D]">
              {sectionName}
              {section.isRequired && <span className="text-red-500 ml-1">*</span>}
            </h2>
            {section.description && (
              <p className="text-[12px] text-gray-500">{section.description}</p>
            )}
          </div>
        </div>
        <span className="text-[12px] text-[#00293D]/60 bg-[#E58625]/10 px-3 py-1 rounded-full">
          {displayEntries.length} {displayEntries.length === 1 ? 'entry' : 'entries'}
        </span>
      </div>

      {/* Entries */}
      <div className="space-y-4">
        {displayEntries.map((entry, entryIndex) => {
          const isExpanded = expandedEntries.has(entryIndex);
          const entryTitle = getEntryTitle(entry, entryIndex);
          const entryErrors = errors?.[entryIndex] || {};

          return (
            <div
              key={entryIndex}
              className="border border-[#00293D]/10 rounded-[15px] overflow-hidden"
            >
              {/* Entry Header - Collapsible */}
              <div
                className="flex items-center justify-between px-4 py-3 bg-[#F8F9FA] cursor-pointer hover:bg-[#F0F1F3] transition-colors"
                onClick={() => toggleExpand(entryIndex)}
              >
                <div className="flex items-center gap-3">
                  <button
                    type="button"
                    className="w-6 h-6 flex items-center justify-center text-[#00293D]/60"
                  >
                    <svg
                      className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                  <span className="text-[14px] font-semibold font-serif text-[#00293D]">
                    {entryTitle}
                  </span>
                </div>
                {displayEntries.length > 1 && (
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleRemoveEntry(entryIndex);
                    }}
                    className="text-red-500 hover:text-red-700 text-[12px] font-medium flex items-center gap-1"
                  >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                    Remove
                  </button>
                )}
              </div>

              {/* Entry Fields - Collapsible */}
              {isExpanded && (
                <div className="p-4 space-y-4">
                  {activeFields.map((field) => (
                    <DynamicField
                      key={field.id}
                      field={field}
                      value={entry[field.slug]}
                      onChange={(fieldSlug, value) => handleFieldChange(entryIndex, fieldSlug, value)}
                      error={entryErrors[field.slug]}
                    />
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Add Entry Button */}
      <button
        type="button"
        onClick={handleAddEntry}
        className="mt-4 w-full py-3 border-2 border-dashed border-[#E58625]/40 rounded-[15px] text-[14px] font-semibold font-serif text-[#E58625] hover:border-[#E58625] hover:bg-[#E58625]/5 transition-colors flex items-center justify-center gap-2"
      >
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
        </svg>
        Add Another {sectionName}
      </button>
    </div>
    </RepeatableSectionErrorBoundary>
  );
}
