'use client';
import { useState, useEffect } from 'react';
import { FaTrashAlt, FaPencilAlt, FaCheck, FaTimes } from 'react-icons/fa';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { SearchableSelect } from '@/components/ui/searchable-select';
import { KeyValueRepeaterProps, KeyValuePair } from '@/types/common';

export function KeyValueRepeater({
  availableKeys,
  initialPairs = [],
  onChange,
  keyPlaceholder = 'Key',
  valuePlaceholder = 'Value',
  className,
  isSecret = false,
}: KeyValueRepeaterProps) {
  const [pairs, setPairs] = useState<KeyValuePair[]>(
    initialPairs.map((pair) => ({
      ...pair,
      isEditing: false,
      tempValue: '',
      id: crypto.randomUUID(),
    }))
  );

  useEffect(() => {
    if (onChange) {
      onChange(pairs);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pairs]);

  const addPair = () => {
    const newPair: KeyValuePair = {
      id: crypto.randomUUID(),
      key: '',
      value: '',
      isEditing: false,
      tempValue: '',
    };

    setPairs((prevPairs) => {
      const newPairs = [...prevPairs, newPair];
      return newPairs;
    });
  };

  const removePair = (id?: string) => {
    setPairs((prevPairs) => {
      const newPairs = prevPairs.filter((pair) => pair.id !== id);
      return newPairs;
    });
  };

  const updatePair = (field: 'key' | 'value' | 'tempValue', newValue: string, id?: string) => {
    const newPairs = pairs.map((pair) => {
      if (pair.id === id) {
        return { ...pair, [field]: newValue };
      }
      return pair;
    });

    setPairs(newPairs);
  };

  const startEditing = (id?: string) => {
    setPairs((prev) =>
      prev.map((pair) => ({
        ...pair,
        isEditing: pair.id === id ? true : pair.isEditing,
        tempValue: pair.id === id ? '' : pair.tempValue,
      }))
    );
  };

  const cancelEditing = (id?: string) => {
    setPairs((prev) =>
      prev.map((pair) => ({
        ...pair,
        isEditing: pair.id === id ? false : pair.isEditing,
        tempValue: '',
      }))
    );
  };

  const saveEdit = (id?: string) => {
    setPairs((prevPairs) => {
      const updatedPairs = prevPairs.map((pair) => {
        if (pair.id === id && pair.tempValue) {
          return {
            ...pair,
            value: pair.tempValue,
            isEditing: false,
            tempValue: '',
          };
        }
        return pair;
      });

      return updatedPairs;
    });
  };

  const getMaskedValue = (value: string) => '•'.repeat(Math.min(12, value.length || 8));

  return (
    <>
      <div className={`space-y-4 rounded-sm ${pairs.length > 0 ? 'py-2' : ''} ${className}`}>
        {pairs.map((pair) => (
          <div key={pair.id} className='flex gap-1 items-start'>
            {availableKeys ? (
              <SearchableSelect
                options={availableKeys}
                value={pair.key}
                onChange={(value) => updatePair('key', String(value), pair.id)}
                className='w-[100px]'
                buttonClassName='p-2'
              />
            ) : (
              <Input
                value={pair.key}
                onChange={(e) => updatePair('key', e.target.value, pair.id)}
                placeholder={keyPlaceholder}
                className='flex-1 border-neutral-300 bg-neutral-200 rounded-sm text-neutral-800 placeholder:text-neutral-500'
              />
            )}

            <div className='flex-1 flex gap-1'>
              {isSecret && pair.isEditing ? (
                <Input
                  type='text'
                  value={pair.tempValue}
                  onChange={(e) => updatePair('tempValue', e.target.value, pair.id)}
                  placeholder='Enter new value'
                  className='flex-1 border-neutral-300 bg-neutral-200 rounded-sm text-neutral-800 placeholder:text-neutral-500'
                />
              ) : (
                <Input
                  type='text'
                  value={isSecret ? getMaskedValue(pair.value) : pair.value}
                  onChange={(e) => updatePair('value', e.target.value, pair.id)}
                  placeholder={valuePlaceholder}
                  className='flex-1 border-neutral-300 bg-neutral-200 rounded-sm text-neutral-800 placeholder:text-neutral-500'
                  readOnly={isSecret}
                />
              )}

              {isSecret && (
                <>
                  {pair.isEditing ? (
                    <>
                      <Button
                        type='button'
                        variant='ghost'
                        size='icon'
                        onClick={() => saveEdit(pair.id)}
                        className='text-green-700 hover:bg-transparent hover:text-green-800 w-auto'
                        disabled={!pair.tempValue}
                      >
                        <FaCheck className='!h-4 !w-4' />
                      </Button>
                      <Button
                        type='button'
                        variant='ghost'
                        size='icon'
                        onClick={() => cancelEditing(pair.id)}
                        className='text-red-700 hover:bg-transparent hover:text-red-800 w-auto'
                      >
                        <FaTimes className='!h-4 !w-4' />
                      </Button>
                    </>
                  ) : (
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      onClick={() => startEditing(pair.id)}
                      className='text-neutral-400 hover:bg-transparent hover:text-neutral-50 w-auto'
                    >
                      <FaPencilAlt className='!h-4 !w-4' />
                    </Button>
                  )}
                </>
              )}
            </div>

            <Button
              type='button'
              variant='ghost'
              size='icon'
              onClick={() => removePair(pair.id)}
              className='text-neutral-400 hover:bg-transparent hover:text-neutral-50 w-auto'
            >
              <FaTrashAlt className='!h-4 !w-4' />
            </Button>
          </div>
        ))}
      </div>
      <Button onClick={addPair} type='button' variant='light-outline' className='w-full'>
        Add Item
      </Button>
    </>
  );
}
