'use client';

import { useState, useEffect } from 'react';
import { PaymentMethodField, PAYMENT_FIELD_TYPES, PaymentFieldType } from './types';
import FormLabel from '@/Component/Common/Forms/FormLabel';
import { TableDeleteSVG } from '@/Component/Common/SVGs/CommonSVG';
import FormikInput from '@/Component/Common/Forms/FormikInput';
import FormikSelect from '@/Component/Common/Forms/FormikSelect';

export const generateFieldKey = (label: string, existingKeys: string[]) => {
  const base = (label || 'field')
    .toLowerCase()
    .replace(/\s+/g, '_')
    .replace(/[^a-z0-9_]/g, '');
  let key = base;
  let i = 0;
  while (existingKeys.includes(key)) {
    key = `${base}_${++i}`;
  }
  return key;
};

interface DynamicFieldEditorProps {
  json_text: PaymentMethodField[];
  onChange: (json_text: PaymentMethodField[]) => void;
  errors?: Record<string, string>;
  touched?: Record<string, boolean>;
  getFieldProps: (field: string) => { name: string; value: any; onChange: (e: any) => void; onBlur: (e: any) => void };
}

export default function DynamicFieldEditor({
  json_text,
  onChange,
  errors = {},
  touched = {},
  getFieldProps,
}: DynamicFieldEditorProps) {
  // Store raw input values for options to allow typing commas freely
  const [optionsInputs, setOptionsInputs] = useState<Record<number, string>>({});

  // Initialize options inputs from json_text when fields change or type changes to select
  useEffect(() => {
    const inputs: Record<number, string> = {};
    json_text.forEach((field, index) => {
      if (field.type === 'select') {
        // Initialize from field.options if available, otherwise keep existing or set empty
        if (field.options && field.options.length > 0) {
          const optionsStr = field.options.join(', ');
          // Only update if it's different (to avoid overwriting user input)
          if (!optionsInputs[index] || optionsInputs[index] !== optionsStr) {
            inputs[index] = optionsStr;
          }
        } else if (!(index in optionsInputs)) {
          inputs[index] = '';
        }
      }
    });
    if (Object.keys(inputs).length > 0) {
      setOptionsInputs((prev) => ({ ...prev, ...inputs }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [json_text.length, json_text.map(f => `${f.type}-${f.options?.length || 0}`).join('|')]);

  const addField = () => {
    const existingKeys = json_text.map((f) => f.key);
    const newKey = generateFieldKey('new_field', existingKeys);
    onChange([
      ...json_text,
      { key: newKey, label: 'New Field', type: 'text', required: false },
    ]);
  };

  const removeField = (index: number) => {
    const newInputs = { ...optionsInputs };
    delete newInputs[index];
    // Reindex remaining inputs
    const reindexed: Record<number, string> = {};
    Object.keys(newInputs).forEach((key) => {
      const oldIndex = Number(key);
      if (oldIndex > index) {
        reindexed[oldIndex - 1] = newInputs[oldIndex];
      } else if (oldIndex < index) {
        reindexed[oldIndex] = newInputs[oldIndex];
      }
    });
    setOptionsInputs(reindexed);
    onChange(json_text.filter((_, i) => i !== index));
  };

  const updateField = (index: number, updates: Partial<PaymentMethodField>) => {
    const next = [...json_text];
    next[index] = { ...next[index], ...updates };
    onChange(next);
  };

  const handleOptionsInputChange = (index: number, value: string) => {
    // Update the raw input value (allows typing commas freely)
    setOptionsInputs((prev) => ({ ...prev, [index]: value }));
  };

  const handleOptionsInputBlur = (index: number) => {
    // On blur, parse and save the options array
    const rawValue = optionsInputs[index] || '';
    const options = rawValue
      .split(',')
      .map((o) => o.trim())
      .filter(Boolean);
    updateField(index, { options });
    // Update the display value to cleaned version
    setOptionsInputs((prev) => ({ ...prev, [index]: options.join(', ') }));
  };

  return (
    <div className="space-y-4 mt-4">
      <div className="flex items-center justify-between">
        <FormLabel title="Dynamic Fields" customClass="!mb-0 !font-medium" />
        <button
          type="button"
          onClick={addField}
          className="text-primary font-medium hover:underline text-sm"
        >
          + Add field
        </button>
      </div>
      {json_text.map((field, index) => (
        <div
          key={`field-${index}`}
          className="p-3 border border-lightGray rounded-lg space-y-3 bg-gray/5"
        >
          {/* First line: Label, Type, Required checkbox, Delete button */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3 flex-wrap">
              <div className="">
                <FormLabel title="Label" />
                <FormikInput
                  inputProps={{
                    type: 'text',
                    name: 'label',
                    value: field.label,
                    onChange: (e) => updateField(index, { label: e.target.value }),
                  }}
                />
              </div>
              <div className="min-w-[200px]">
                <FormLabel title="Type" />
                <FormikSelect
                  selectProps={{
                    name: 'type',
                    value: field.type,
                    onChange: (e) => updateField(index, { type: e.target.value as PaymentFieldType }),
                  }}
                  customClass="!rounded-2xl !py-3 !border-neutral-200"
                  children={PAYMENT_FIELD_TYPES.map((t) => (
                    <option key={t.value} value={t.value}>
                      {t.label}
                    </option>))}
                />
              </div>
              <div>
                <FormLabel title="Is Required?" />
                <div className="flex items-center border border-neutral-200 divide-x divide-gray rounded-2xl overflow-hidden min-w-[150px] bg-white text-sm">
                  <label className="flex-1 relative cursor-pointer">
                    <input
                      type="radio"
                      name={`required-${index}`}
                      checked={field.required === true}
                      onChange={() => updateField(index, { required: true })}
                      className="hidden peer"
                    />
                    <span className="peer-checked:bg-gradient-to-br peer-checked:from-secondary peer-checked:to-primary peer-checked:text-white peer-checked:font-medium text-center py-3 px-4 block transition-all">
                      Yes
                    </span>
                  </label>
                  <label className="flex-1 relative cursor-pointer">
                    <input
                      type="radio"
                      name={`required-${index}`}
                      checked={field.required === false}
                      onChange={() => updateField(index, { required: false })}
                      className="hidden peer"
                    />
                    <span className="peer-checked:bg-gradient-to-br peer-checked:from-secondary peer-checked:to-primary peer-checked:text-white peer-checked:font-medium text-center py-3 px-4 block transition-all">
                      No
                    </span>
                  </label>
                </div>
              </div>
            </div>
            <button
              type="button"
              onClick={() => removeField(index)}
              className="p-1 text-red-500 hover:bg-red-50 rounded self-end mb-2"
              title="Remove field"
            >
              <TableDeleteSVG />
            </button>
          </div>

          {/* New line: Options input (only for select type) */}
          {field.type === 'select' && (
            <div className="mt-2">
              <FormLabel title="Options (comma separated)" />
              <FormikInput
                inputProps={{
                  placeholder: 'Option 1, Option 2, Option 3',
                  type: 'text',
                  name: 'options',
                  value: optionsInputs[index] ?? '',
                  onChange: (e) => handleOptionsInputChange(index, e.target.value),
                  onBlur: () => handleOptionsInputBlur(index),
                }}
                customClass="w-full"
              />
            </div>
          )}
        </div>
      ))}
    </div>
  );
}
