"use client";

import React from 'react';
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import Image from 'next/image';

interface IndustryItem {
  id: number;
  title: string;
  shortDescription: string;
  longDescription: string;
  sequence: number;
  subsections: Array<{ id: number; title: string; description: string }>;
}

export function IndustryAccordion({ industries }: { industries: IndustryItem[] }) {

  const firstIndustryId = industries.length > 0 ? industries[0].id : null;
  const defaultValue = firstIndustryId ? `industry-${firstIndustryId}` : undefined;

  return (
    <Accordion
      type="single"
      collapsible
      defaultValue={defaultValue}
      className="w-full space-y-4"
    >
      {industries.map((industry) => (
        <AccordionItem
          key={industry.id}
          value={`industry-${industry.id}`}
          className="border border-gray-200 rounded-md overflow-hidden"
        >
          <AccordionTrigger className="text-lg font-medium text-gray-700 hover:no-underline flex items-center justify-between px-4 py-3  hover:bg-gray-100 [&>svg]:hidden">
            <div className="flex items-center gap-2 text-[18px] md:text-[24px] font-normal">
              <Image
                src="/assets/images/arrow-down.png"
                alt="arrow"
                width={16}
                height={16}
                className="w-4 h-4 transition-transform duration-200 accordion-icon"
              />
              {industry.title}
            </div>
          </AccordionTrigger>

          <AccordionContent className="px-0 py-0">
            {industry.shortDescription && (
              <SolventList html={industry.shortDescription} />
            )}
          </AccordionContent>
        </AccordionItem>
      ))}
    </Accordion>
  );
}

// Parse HTML and extract heading + table rows → render with bullet images
function SolventList({ html }: { html: string }) {
  const [solvents, setSolvents] = React.useState<string[]>([]);
  const [heading, setHeading] = React.useState<string>('');

  React.useEffect(() => {
    try {
      const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      const table = doc.querySelector('table');

      if (table) {

        const th = table.querySelector('thead th');
        setHeading(th ? th.textContent?.trim() || '' : '');


        const tbody = table.querySelector('tbody') || table;
        const rows = Array.from(tbody.querySelectorAll('tr'))
          .map((tr) => {
            const td = tr.querySelector('td');
            return td ? td.textContent?.trim() : undefined;
          })
          .filter((text): text is string => Boolean(text));

        setSolvents(rows);
      } else {

        const lines = html
          .split('\n')
          .map((l) => l.trim())
          .filter((l) => l.length > 0);
        setSolvents(lines);
      }
    } catch (e) {
      console.error('Error parsing solvent list:', e);
      setSolvents([html]);
    }
  }, [html]);

  return (
    <div className="bg-blue-50 rounded-md border border-blue-100">
      {heading && (
        <div className="px-4 py-2 font-semibold text-gray-800 bg-blue-100 text-[16px]">
          {heading}
        </div>
      )}

      <ul className="p-4 space-y-2">
        {solvents.map((solvent, idx) => (
          <li key={idx} className="flex items-start gap-2 text-[15px]">
            <Image
              src="/assets/images/bullet.png"
              alt="bullet"
              width={16}
              height={16}
              className="inline-block mt-1"
            />
            <span className="text-gray-700">{solvent}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}