'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-20 text-center text-secondary">
        <Package size={48} className="mx-auto mb-4 opacity-10" />
        <p className="font-normal">No results found</p>
      </div>
    );
  }

  return (
    <section className="space-y-3">
      {categories.map(cat => {
        const categoryItems = items.filter(i => i.category === cat);
        return (
          <div key={cat} className="bg-surface/50 border border-outline/20 overflow-hidden transition-all duration-300">
            <div
              className="w-full p-4 md:p-5 flex items-center justify-between hover:bg-surface/60 transition-colors cursor-pointer"
              onClick={() => onExpandCategory(expandedCategory === cat ? null : cat)}
            >
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 bg-primary/10 flex items-center justify-center text-primary transition-colors">
                  <Layers size={20} />
                </div>
                <div className="text-left">
                  <h3 className="card-title text-base sm:text-lg">{cat}</h3>
                  <p className="card-subtitle tracking-tight">
                    {categoryItems.length} Item types in stock
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                {expandedCategory === cat ? <ChevronDown size={20} className="text-primary" /> : <ChevronRight size={20} className="text-secondary" />}
                {onEditCategory && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onEditCategory(cat);
                    }}
                    className="p-2 hover:bg-surface-container text-secondary hover:text-primary transition-colors relative z-10"
                  >
                    <EditIcon size={16} />
                  </button>
                )}
              </div>
            </div>

            {expandedCategory === cat && (
              <div className="p-4 pt-0 space-y-2 animate-in slide-in-from-top-4 duration-300">
                <div className="h-px bg-outline/20 mb-4 mx-2" />
                {categoryItems.map(item => (
                  <div
                    key={item.id}
                    className="bg-background/40 border border-outline/20 p-4 flex items-center justify-between hover:border-primary/40 transition-all active:scale-[0.98]"
                  >
                    <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-12 h-12 shrink-0 border border-outline/30 overflow-hidden cursor-pointer hover:border-primary transition-colors active:scale-95"
                        >
                          <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-12 h-12 bg-success/10 flex items-center justify-center text-success shrink-0">
                          <Package size={14} />
                        </div>
                      )}
                      <div className="truncate">
                        <h4 className="card-title truncate">{item.name}</h4>
                        {item.photo_path || item.image_url ? (
                          <p className="card-subtitle mt-0 opacity-80 text-xs">Tap photo for details</p>
                        ) : (
                          <>
                            <p className="card-subtitle mt-0 opacity-80 truncate">{item.specs}</p>
                            <p className="card-subtitle mt-0 text-xs">No photo</p>
                          </>
                        )}
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <span className={cn(
                        "text-lg font-normal",
                        item.quantity <= item.min_quantity ? "text-warning" : "text-primary"
                      )}>
                        {item.quantity}
                      </span>
                      <p className="text-sm text-secondary font-normal tracking-tight">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>
  );
}
