'use client';

import { useState, useEffect } from 'react';
import ProductReviews from '@/components/product/ProductReviews';
import type { ProductReview } from '@/lib/shopware-api';

interface ProductProperty {
  id: string;
  name: string;
  options: Array<{ id: string; name: string }>;
}

interface ProductDetailTabsProps {
  productId: string;
  productName: string;
  description: string | null;
  properties?: ProductProperty[];
  initialReviews: ProductReview[];
  initialTotal: number;
  ratingAverage: number | null;
}

export default function ProductDetailTabs({
  productId,
  productName,
  description,
  properties = [],
  initialReviews,
  initialTotal,
  ratingAverage,
}: ProductDetailTabsProps) {
  const [activeTab, setActiveTab] = useState<'description' | 'reviews'>('description');

  // Switch to reviews tab when #reviews hash is present or clicked
  useEffect(() => {
    const handleHash = () => {
      if (window.location.hash === '#reviews') {
        setActiveTab('reviews');
      }
    };
    handleHash();
    window.addEventListener('hashchange', handleHash);
    return () => window.removeEventListener('hashchange', handleHash);
  }, []);

  const hasProperties = properties.length > 0;
  const hasDescriptionTab = Boolean(description) || hasProperties;

  const tabs = [
    ...(hasDescriptionTab ? [{ id: 'description' as const, label: 'Description' }] : []),
    { id: 'reviews' as const, label: 'Reviews' },
  ];

  // If there's nothing to show in the description tab, default to reviews
  const currentTab = !hasDescriptionTab && activeTab === 'description' ? 'reviews' : activeTab;

  return (
    <div id="reviews">
      {/* Tab Headers */}
      <div className="border-b border-surface-200 mb-6">
        <div className="flex gap-6">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`pb-3 text-base font-medium transition-colors relative ${
                currentTab === tab.id
                  ? 'text-brand-600'
                  : 'text-surface-500 hover:text-surface-700'
              }`}
            >
              {tab.label}
              {currentTab === tab.id && (
                <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-brand-600" />
              )}
            </button>
          ))}
        </div>
      </div>

      {/* Tab Content */}
      {currentTab === 'description' && hasDescriptionTab && (
        <div>
          <h2 className="text-xl font-bold text-surface-900 mb-4">
            Product information &quot;{productName}&quot;
          </h2>
          {description && (
            <div
              className="prose prose-base max-w-none text-surface-700 prose-headings:text-surface-900 prose-a:text-brand-600"
              dangerouslySetInnerHTML={{ __html: description }}
            />
          )}

          {/* Properties table — mirrors Shopware's product.sortedProperties */}
          {hasProperties && (
            <div className="mt-8 max-w-2xl">
              <table className="w-full text-sm border-collapse">
                <tbody>
                  {properties.map((group, i) => (
                    <tr
                      key={group.id}
                      className={i % 2 === 0 ? 'bg-surface-50' : undefined}
                    >
                      <th className="text-left font-semibold text-surface-900 align-top py-3 px-4 w-1/2">
                        {group.name}:
                      </th>
                      <td className="text-surface-700 py-3 px-4">
                        {group.options.map((o) => o.name).join(', ')}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {currentTab === 'reviews' && (
        <ProductReviews
          productId={productId}
          initialReviews={initialReviews}
          initialTotal={initialTotal}
          ratingAverage={ratingAverage}
        />
      )}
    </div>
  );
}
