'use client';

import { useState } from 'react';
import { Item } from '@/lib/db';
import { buildPhotoUrl } from '@/lib/api';
import { ChevronRight, ChevronDown, Layers, Package } from 'lucide-react';
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
import ItemDetailModal from '@/components/ItemDetailModal';
import PhotoModal from '@/components/PhotoModal';

function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

interface InventoryTableProps {
  items: Item[];
  categories: string[];
  expandedCategory: string | null;
  onExpandCategory: (category: string | null) => void;
  onItemClick: (item: Item) => void;
  onEditCategory?: (category: string) => void;
  categoriesList?: any[];
  backendUrl?: string;
}

export default function InventoryTable({
  items,
  categories,
  expandedCategory,
  onExpandCategory,
  onItemClick,
  onEditCategory,
  categoriesList = [],
  backendUrl = ''
}: InventoryTableProps) {
  const [selectedItemDetail, setSelectedItemDetail] = useState<Item | null>(null);
  const [refreshTrigger, setRefreshTrigger] = useState(0);
  const [selectedPhotoItem, setSelectedPhotoItem] = useState<Item | null>(null);

  const handleItemClick = (item: Item) => {
    setSelectedItemDetail(item);
    onItemClick(item);
  };

  const handleCloseDetail = () => {
    setSelectedItemDetail(null);
  };

  const handleItemRefresh = () => {
    setRefreshTrigger(prev => prev + 1);
  };

  if (categories.length === 0) {
    return (
      <div className="py-2 lg:py-3 xl:py-40 text-center text-[#888888]">
        <Package size={48} className="mx-auto mb-4 opacity-10" />
        <p className="font-normal">No Results Found</p>
      </div>
    );
  }

  return (
    <section className="space-y-4">
      {categories.map(cat => {
        const categoryItems = items.filter(i => i.category === cat);
        return (
          <div key={cat} className="level-1 transition-all duration-300">
            <div
              className="w-full p-2 md:p-3 flex items-center justify-between hover:bg-black/40 transition-colors cursor-pointer"
              onClick={() => onExpandCategory(expandedCategory === cat ? null : cat)}
            >
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 bg-black flex items-center justify-center text-primary border border-primary/20 transition-colors">
                  <Layers size={16} />
                </div>
                <div className="text-left">
                  <h3 className="text-sm md:text-base font-normal text-foreground">{cat}</h3>
                  <p className="text-[10px] text-secondary font-normal">
                    {categoryItems.length} Item Types In Stock
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                {expandedCategory === cat ? <ChevronDown size={18} className="text-primary" /> : <ChevronRight size={18} className="text-secondary" />}
                {onEditCategory && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onEditCategory(cat);
                    }}
                    className="p-1.5 hover:bg-black text-secondary hover:text-primary transition-colors border border-transparent hover:border-border"
                  >
                    <EditIcon size={14} />
                  </button>
                )}
              </div>
            </div>

            {expandedCategory === cat && (
              <div className="divide-y divide-border border-t border-border animate-in slide-in-from-top-2 duration-200">
                {categoryItems.map(item => (
                  <div
                    key={item.id}
                    className="bg-black/40 p-2 md:p-3 flex items-center justify-between hover:bg-black transition-colors"
                  >
                    <div
                      onClick={() => handleItemClick(item)}
                      className="flex items-center gap-3 flex-1 min-w-0 pr-4 cursor-pointer"
                    >
                      {item.photo_path || item.image_url ? (
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                            setSelectedPhotoItem(item);
                          }}
                          className="w-10 h-10 shrink-0 border border-border overflow-hidden cursor-pointer hover:border-primary transition-colors"
                        >
                          <img
                            src={buildPhotoUrl(backendUrl, item.photo_path || item.image_url || '')}
                            alt={item.name}
                            className="w-full h-full object-cover"
                            loading="lazy"
                          />
                        </div>
                      ) : (
                        <div className="w-10 h-10 bg-black flex items-center justify-center text-primary shrink-0 border border-primary/20">
                          <Package size={14} />
                        </div>
                      )}
                      <div className="truncate">
                        <h4 className="text-sm font-normal text-foreground truncate">{item.name}</h4>
                        <p className="text-[10px] text-secondary font-normal truncate">
                          {item.specs || (item.photo_path || item.image_url ? 'Tap Photo For Details' : 'No Specs')}
                        </p>
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <span className={cn(
                        "text-base font-normal tabular-nums",
                        item.quantity <= item.min_quantity ? "text-rose-500" : "text-primary"
                      )}>
                        {item.quantity}
                      </span>
                      <p className="text-[10px] text-secondary font-normal">Stock</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })}

      {selectedItemDetail && (
        <ItemDetailModal
          item={selectedItemDetail}
          onClose={handleCloseDetail}
          onItemRefresh={handleItemRefresh}
          backendUrl={backendUrl}
        />
      )}

      {selectedPhotoItem && (selectedPhotoItem.photo_path || selectedPhotoItem.image_url) && (
        <PhotoModal
          photoUrl={selectedPhotoItem.photo_path || selectedPhotoItem.image_url || ''}
          title={selectedPhotoItem.name}
          onClose={() => setSelectedPhotoItem(null)}
        />
      )}
    </section>
  );
}

// EditIcon component (lucide-react equivalent)
function EditIcon({ size = 24 }: { size?: number }) {
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
    </svg>
  );
}
