'use client';
import { SocialsRepeater } from '@/components/builder/common/SocialsRepeater';
import { Button } from '@/components/ui/button';
import { IconPicker } from '@/components/ui/icon-picker';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { EditFormProps } from '@/types/common';
import { Plus, Trash2 } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Social } from '@/types/social';
import { NavItem } from '@/types/header';
import { ComponentStyler } from '@/components/builder/common/ComponentStyler';
import { PortfolioElement } from '@/src/types/portfolio';

export function HeaderEditForm({ props, onPropChange, layout }: EditFormProps) {
  const socials = (props.socials as Social[]) || [];
  const navItems = (props.items as NavItem[]) || [];
  const [itemKeys, setItemKeys] = useState<string[]>([]);

  useEffect(() => {
    if (itemKeys.length < navItems.length) {
      const newKeys = [...itemKeys];
      for (let i = itemKeys.length; i < navItems.length; i++) {
        newKeys.push(crypto.randomUUID());
      }
      setItemKeys(newKeys);
    }
  }, [navItems.length, itemKeys]);

  const showThemeToggle = props.showThemeToggle as boolean;
  const buttonText = props.buttonText as string;
  const buttonHref = props.buttonHref as string;

  const handleNavItemChange = (index: number, field: 'text' | 'href', value: string) => {
    const newItems = Array.isArray(props.items) ? [...props.items] : [];
    newItems[index] ??= { text: '', href: '' };
    newItems[index][field] = value;
    onPropChange('items', newItems);
  };

  const handleRemoveNavItem = (index: number) => {
    const newItems = navItems.filter((_, i) => i !== index);
    onPropChange('items', newItems);
  };

  const handleSocialChange = (socials: { platform: string; url: string }[]) => {
    onPropChange('socials', socials);
  };

  return (
    <div className='space-y-4'>
      <div className='space-y-2'>
        <Label>Icon</Label>
        <IconPicker value={props.logo as string} onChange={(value) => onPropChange('logo', value as string)} />
      </div>

      {layout === 'header_1' && (
        <div className='space-y-2'>
          <Label>Navigation Links</Label>
          {navItems.map((item, index) => (
            <div key={itemKeys[index] || index} className='flex gap-2'>
              <Input
                value={item.text || ''}
                onChange={(e) => handleNavItemChange(index, 'text', e.target.value)}
                placeholder='Section Name'
                className='flex-1'
              />
              <Input
                value={item.href || ''}
                onChange={(e) => handleNavItemChange(index, 'href', e.target.value)}
                placeholder='Id'
                className='flex-1'
              />
              <button
                onClick={() => {
                  handleRemoveNavItem(index);
                  setItemKeys((prev) => prev.filter((_, i) => i !== index));
                }}
                className='p-2 text-neutral-200'
                aria-label='Remove link'
              >
                <Trash2 className='h-4 w-4' />
              </button>
            </div>
          ))}
          <Button
            onClick={() => {
              onPropChange('items', [...navItems, { text: '', href: '' }]);
              setItemKeys((prev) => [...prev, crypto.randomUUID()]);
            }}
            className='text-sm flex items-center gap-1 w-full'
            variant='light-outline'
          >
            <Plus className='h-4 w-4' />
            Add Link
          </Button>
        </div>
      )}

      {layout === 'header_2' && (
        <div className='space-y-2'>
          <Label>Button</Label>
          <Input
            value={buttonText}
            onChange={(e) => onPropChange('buttonText', e.target.value)}
            placeholder='Button text'
          />
          <Label>Button URL</Label>
          <Input
            value={buttonHref}
            onChange={(e) => onPropChange('buttonHref', e.target.value)}
            placeholder='Button URL'
          />
        </div>
      )}

      {layout === 'header_3' && <SocialsRepeater socials={socials} onChange={handleSocialChange} />}

      <div className='flex items-center justify-between'>
        <Label>Show Theme Toggle</Label>
        <Switch checked={showThemeToggle} onCheckedChange={(checked) => onPropChange('showThemeToggle', checked)} />
      </div>
      <ComponentStyler
        styling={props.styling as PortfolioElement['styling']}
        onStylingChange={(styling) => onPropChange('styling', styling)}
        enabledOptions={{
          backgroundColor: true,
          padding: true,
          textColor: true,
        }}
      />
    </div>
  );
}
