'use client';

import { useState } from 'react';
import { Plus, Trash2 } from 'lucide-react'; // icons (optional)

interface Column {
  key: string;
  label: string;
  type: 'text' | 'number' | 'select';
  options?: string[];
}

export default function TableBuilder() {
  const [columns, setColumns] = useState<Column[]>([
    { key: 'sieve_opening', label: 'Sieve Opening', type: 'text' },
  ]);
  const [rows, setRows] = useState<any[]>([{ sieve_opening: '' }]);

  // ➕ Add a new column
  const addColumn = () => {
    const newKey = `col_${columns.length + 1}`;
    setColumns([
      ...columns,
      { key: newKey, label: `Column ${columns.length + 1}`, type: 'text' },
    ]);
    setRows(rows.map((r) => ({ ...r, [newKey]: '' })));
  };

  // 🗑️ Remove a column
  const removeColumn = (key: string) => {
    setColumns(columns.filter((c) => c.key !== key));
    setRows(
      rows.map((r) => {
        const { [key]: _, ...rest } = r;
        return rest;
      }),
    );
  };

  // ➕ Add a new row
  const addRow = () => {
    const emptyRow = columns.reduce(
      (acc, col) => ({ ...acc, [col.key]: '' }),
      {},
    );
    setRows([...rows, emptyRow]);
  };

  // ✏️ Handle cell change
  const handleChange = (rowIndex: number, key: string, value: string) => {
    const updated = [...rows];
    updated[rowIndex][key] = value;
    setRows(updated);
  };

  return (
    <div className="bg-card text-card-foreground border rounded-2xl shadow-sm p-6 space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Dynamic Table Builder</h2>
        <button
          onClick={addColumn}
          className="inline-flex items-center gap-2 px-3 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition"
        >
          <Plus size={16} /> Add Column
        </button>
      </div>

      {/* Columns Configurator */}
      <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
        {columns.map((col, i) => (
          <div
            key={col.key}
            className="p-4 border rounded-xl bg-muted/30 flex flex-col gap-2"
          >
            <label className="text-sm font-medium">Column Label</label>
            <input
              className="input input-bordered w-full"
              value={col.label}
              onChange={(e) => {
                const updated = [...columns];
                updated[i].label = e.target.value;
                setColumns(updated);
              }}
            />

            <label className="text-sm font-medium">Type</label>
            <select
              className="input input-bordered w-full"
              value={col.type}
              onChange={(e) => {
                const updated = [...columns];
                updated[i].type = e.target.value as any;
                setColumns(updated);
              }}
            >
              <option value="text">Text</option>
              <option value="number">Number</option>
              <option value="select">Select</option>
            </select>

            <button
              onClick={() => removeColumn(col.key)}
              className="mt-2 inline-flex items-center justify-center gap-2 text-sm text-destructive hover:text-destructive/80"
            >
              <Trash2 size={14} /> Remove
            </button>
          </div>
        ))}
      </div>

      {/* Table Preview */}
      <div className="overflow-x-auto border rounded-xl">
        <table className="w-full border-collapse text-sm">
          <thead className="bg-muted">
            <tr>
              {columns.map((col) => (
                <th
                  key={col.key}
                  className="border-b px-4 py-2 text-left font-medium"
                >
                  {col.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, rowIndex) => (
              <tr key={rowIndex} className="odd:bg-muted/20">
                {columns.map((col) => (
                  <td key={col.key} className="border-b px-4 py-2">
                    <input
                      type={col.type === 'select' ? 'text' : col.type}
                      value={row[col.key] ?? ''}
                      onChange={(e) =>
                        handleChange(rowIndex, col.key, e.target.value)
                      }
                      className="w-full bg-transparent border border-input rounded-md px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
                    />
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="flex justify-end">
        <button
          onClick={addRow}
          className="inline-flex items-center gap-2 px-3 py-2 bg-primary text-white rounded-lg hover:bg-primary/80 transition"
        >
          <Plus size={16} /> Add Row
        </button>
      </div>
    </div>
  );
}
