import React, { useState, useCallback } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import EditableInput from '../shared/EditableInput';

const LayoutGrid = ({ layout, onChange }) => {
  const [items, setItems] = useState(layout?.layoutItems || []);

  const getLastId = useCallback(() => {
    let lastId = 0;
    items.forEach(item => {
      if (item.id > lastId) {
        lastId = item.id;
      }
    });
    return lastId + 1;
  }, [items]);

  const handleAddItem = useCallback(() => {
    const newItem = {
      id: getLastId(),
      parent: 0,
      level: 1,
      loutName: '',
      loutItemName: '',
      loutItemDesc: '',
      loutItemDepth: 1,
      loutItemType: 'Field',
      loutItemOccCnt: '',
      loutItemOccRef: '',
      loutItemDataType: 'String',
      loutItemLength: 1,
      loutItemDecimal: 0,
      loutItemDefault: '',
      loutItemMaskYn: 'N',
      loutItemMaskOffset: 0,
      loutItemMaskLength: 0,
      parentLoutItemIndex: 0,
      expanded: true,
      isLeaf: true,
      LOUTITEMPATH: '',
      value: '',
      loutItemSerno: items.length + 1
    };

    const newItems = [...items, newItem];
    setItems(newItems);
    layout.layoutItems = newItems;
    onChange?.(layout);
  }, [items, layout, onChange, getLastId]);

  const handleMove = useCallback((index, direction) => {
    if ((direction === 'up' && index > 0) ||
        (direction === 'down' && index < items.length - 1)) {
      const newItems = [...items];
      const swapIndex = direction === 'up' ? index - 1 : index + 1;
      [newItems[index], newItems[swapIndex]] = [newItems[swapIndex], newItems[index]];

      // Update loutItemSerno values
      newItems.forEach((item, idx) => {
        item.loutItemSerno = idx + 1;
      });

      setItems(newItems);
      layout.layoutItems = newItems;
      onChange?.(layout);
    }
  }, [items, layout, onChange]);

  const handleDelete = useCallback((index) => {
    const newItems = items.filter((_, idx) => idx !== index);

    // Update loutItemSerno values
    newItems.forEach((item, idx) => {
      item.loutItemSerno = idx + 1;
    });

    setItems(newItems);
    layout.layoutItems = newItems;
    onChange?.(layout);
  }, [items, layout, onChange]);

  const handleFieldChange = useCallback((index, field, value) => {
    const newItems = [...items];
    newItems[index][field] = value;

    if (field === 'value' && newItems[index].value === undefined) {
      newItems[index].value = '';
    }

    setItems(newItems);
    layout.layoutItems = newItems;
    onChange?.(layout);
  }, [items, layout, onChange]);

  return (
      <div className="overflow-x-auto">
        <table className="w-full border-collapse border">
          <thead>
          <tr>
            <th className="border p-2 text-center w-[50px]">#</th>
            <th className="border p-2 text-center w-[80px]">ID</th>
            <th className="border p-2 text-center w-[80px]">Parent</th>
            <th className="border p-2 text-center w-[120px]">항목명(영문)</th>
            <th className="border p-2 text-center w-[150px]">항목설명</th>
            <th className="border p-2 text-center w-[60px]">깊이</th>
            <th className="border p-2 text-center w-[110px]">아이템 유형</th>
            <th className="border p-2 text-center w-[80px]">반복 횟수</th>
            <th className="border p-2 text-center w-[100px]">반복 참조 필드</th>
            <th className="border p-2 text-center w-[80px]">데이터 길이</th>
            <th className="border p-2 text-center w-[120px]">값</th>
            <th className="border p-2 text-center w-[120px]">
              비고
              <Button
                  variant="outline"
                  size="sm"
                  onClick={handleAddItem}
                  className="ml-2"
              >
                <i className="fas fa-plus" />
              </Button>
            </th>
          </tr>
          </thead>
          <tbody>
          {items.map((item, index) => (
              <tr key={item.id} className="layout-grid-row">
                <td className="border p-2 text-center">
                  {item.loutItemSerno}
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.id}
                      onChange={(e) => handleFieldChange(index, 'id', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.parent}
                      onChange={(e) => handleFieldChange(index, 'parent', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.loutItemName}
                      onChange={(e) => handleFieldChange(index, 'loutItemName', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.loutItemDesc}
                      onChange={(e) => handleFieldChange(index, 'loutItemDesc', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="number"
                      value={item.loutItemDepth}
                      onChange={(e) => handleFieldChange(index, 'loutItemDepth', parseInt(e.target.value))}
                      min={1}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Select
                      value={item.loutItemType}
                      onValueChange={(value) => handleFieldChange(index, 'loutItemType', value)}
                      className="w-full"
                  >
                    <option value="Field">Field</option>
                    <option value="Grid">Grid</option>
                    <option value="Group">Group</option>
                    <option value="Attr">Attr</option>
                  </Select>
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.loutItemOccCnt}
                      onChange={(e) => handleFieldChange(index, 'loutItemOccCnt', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="text"
                      value={item.loutItemOccRef}
                      onChange={(e) => handleFieldChange(index, 'loutItemOccRef', e.target.value)}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  <Input
                      type="number"
                      value={item.loutItemLength}
                      onChange={(e) => handleFieldChange(index, 'loutItemLength', parseInt(e.target.value))}
                      min={1}
                      className="w-full"
                  />
                </td>
                <td className="border p-2">
                  {item.loutItemType === 'Field' && (
                      <EditableInput
                          name={`items[${index}].value`}
                          value={item.value}
                          onChange={(value) => handleFieldChange(index, 'value', value)}
                      />
                  )}
                </td>
                <td className="border p-2 text-center">
                  <div className="flex justify-center space-x-1">
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleMove(index, 'up')}
                    >
                      <i className="fas fa-arrow-up" />
                    </Button>
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleMove(index, 'down')}
                    >
                      <i className="fas fa-arrow-down" />
                    </Button>
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleDelete(index)}
                    >
                      <i className="fas fa-trash-alt" />
                    </Button>
                  </div>
                </td>
              </tr>
          ))}
          </tbody>
        </table>
      </div>
  );
};

export default LayoutGrid;
