'use client';

import Image from 'next/image';
import React, { useState, useEffect } from 'react';

export function ProductTable({ html }: { html: string }) {
  const [rows, setRows] = useState<string[][]>([]);
  const [plainTextLines, setPlainTextLines] = useState<string[]>([]);

  useEffect(() => {
    if (!html) return;

    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const table = doc.querySelector('table');

      if (table) {
        const tbody = table.querySelector('tbody') || table;
        const parsedRows: string[][] = [];

        tbody.querySelectorAll('tr').forEach((tr) => {
          const cells = Array.from(tr.querySelectorAll('th, td')).map(
            (cell) => cell.textContent?.trim() || ''
          );
          parsedRows.push(cells);
        });

        setRows(parsedRows);

        
        const paragraphs = Array.from(doc.querySelectorAll('p'))
          .map((p) => p.textContent?.trim() || '')
          .filter((line) => line.length > 0);
        setPlainTextLines(paragraphs);
      } else {
    
        const lines = html
          .split('\n')
          .map((line) => line.trim())
          .filter((line) => line.length > 0);
        setPlainTextLines(lines);
        setRows([]);
      }
    } catch (e) {
      console.error('Error parsing content:', e);
      setPlainTextLines([html]);
    }
  }, [html]);

  return (
    <div className=" overflow-hidden">
      <div className="px-4 py-2 bg-blue-100 text-black font-semibold text-[16px] uppercase tracking-wide">
        Product List
      </div>
      <div className="p-4">
        
        {rows.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-1">
            {rows.map((row, idx) => {
              const [col1, col2] = row;
              return (
                <React.Fragment key={`row-${idx}`}>
                  {col1 && (
                    <div className="flex items-center space-x-2 text-[16.5px] text-gray-700">
                      <Image
                        src="/assets/images/bullet.png"
                        alt="bullet"
                        width={16}
                        height={16}
                        className="inline-block"
                      />
                      <span>{col1}</span>
                    </div>
                  )}
                  {col2 && (
                    <div className="flex items-center space-x-2 text-[16.5px] text-gray-700">
                      <Image
                        src="/assets/images/bullet.png"
                        alt="bullet"
                        width={16}
                        height={16}
                        className="inline-block"
                      />
                      <span>{col2}</span>
                    </div>
                  )}
                </React.Fragment>
              );
            })}
          </div>
        )}

        
        {plainTextLines.length > 0 && (
          <div className="mt-4 text-sm text-gray-700 leading-relaxed space-y-1">
            {plainTextLines.map((line, idx) => (
              <p key={idx} className="mb-1">
                {line.split(' ').map((word, i) => (
                  <span key={i}>{word} </span>
                ))}
              </p>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
