'use client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Plus, Trash2 } from 'lucide-react';
import { useState, useEffect } from 'react';
import { SocialIcons } from '@/components/icons/SocialIcons';
import { SearchableSelect } from '@/components/ui/searchable-select';
import { Label } from '@/components/ui/label';
import { Social } from '@/types/social';

interface SocialsRepeaterProps {
  socials: Social[];
  onChange: (socials: Social[]) => void;
  label?: string;
}

export function SocialsRepeater({ socials, onChange, label = 'Social Links' }: SocialsRepeaterProps) {
  const [itemKeys, setItemKeys] = useState<string[]>([]);
  const [socialItems, setSocialItems] = useState<Social[]>([]);

  useEffect(() => {
    setSocialItems(socials);
  }, [socials]);

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

  const handlePlatformChange = (index: number, platform: string) => {
    const newSocials = [...socialItems];
    newSocials[index] = { ...newSocials[index], platform };
    setSocialItems(newSocials);
    onChange(newSocials);
  };

  const handleUrlChange = (index: number, url: string) => {
    const newSocials = [...socialItems];
    newSocials[index] = { ...newSocials[index], url };
    setSocialItems(newSocials);
    onChange(newSocials);
  };

  const handleRemove = (index: number) => {
    const newSocials = socialItems.filter((_, i) => i !== index);
    setSocialItems(newSocials);
    setItemKeys((prev) => prev.filter((_, i) => i !== index));
    onChange(newSocials);
  };

  const handleAdd = () => {
    const newSocials = [...socialItems, { platform: '', url: '' }];
    setSocialItems(newSocials);
    setItemKeys((prev) => [...prev, crypto.randomUUID()]);
    onChange(newSocials);
  };

  return (
    <div className='space-y-2'>
      <Label>{label}</Label>
      <div className='space-y-2'>
        {socialItems.map((social, index) => (
          <div key={itemKeys[index] || index} className='flex gap-2'>
            <SearchableSelect
              options={Object.keys(SocialIcons).map((platform) => ({
                label: (
                  <div className='flex gap-2 items-center'>
                    {SocialIcons[platform]}
                    <span>{platform}</span>
                  </div>
                ),
                value: platform,
              }))}
              value={social.platform}
              onChange={(value) => handlePlatformChange(index, value as string)}
              className='w-[145px]'
            />
            <Input
              placeholder='URL'
              value={social.url || ''}
              onChange={(e) => handleUrlChange(index, e.target.value)}
              className='flex-1'
            />
            <Button
              type='button'
              variant='ghost'
              size='icon'
              onClick={() => handleRemove(index)}
              className='text-red-500 hover:text-red-600'
            >
              <Trash2 className='h-4 w-4' />
            </Button>
          </div>
        ))}
      </div>
      <Button
        type='button'
        variant='light-outline'
        onClick={handleAdd}
        className='w-full text-sm flex items-center gap-1'
      >
        <Plus className='h-4 w-4' />
        Add Social Link
      </Button>
    </div>
  );
}
