'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 { cn } from '@/lib/utils';
import ItemDetailModal from '@/components/ItemDetailModal';
import PhotoModal from '@/components/PhotoModal';

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 Matching Assets 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">
            <div
              className="w-full p-4 flex items-center justify-between hover:bg-black/30 transition-colors cursor-pointer"
              onClick={() => onExpandCategory(expandedCategory === cat ? null : cat)}
            >
              <div className="flex items-center gap-4">
                <div className="w-10 h-10 bg-black flex items-center justify-center text-primary border border-primary/20 transition-colors">
                  <Layers size={20} />
                </div>
                <div className="text-left">
                  <h3 className="text-base font-normal text-white">{cat}</h3>
                  <p className="text-[10px] text-secondary font-normal mt-0.5">
                    {categoryItems.length} Registered Signatures
                  </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-black text-secondary hover:text-primary transition-colors border border-transparent hover:border-border"
                  >
                    <EditIcon size={16} />
                  </button>
                )}
              </div>
            </div>

            {expandedCategory === cat && (
              <div className="divide-y divide-border border-t border-border animate-in slide-in-from-top-1 duration-200">
                {categoryItems.map(item => (
                  <div
                    key={item.id}
                    className="bg-black/40 p-4 flex items-center justify-between hover:bg-black/20 transition-colors"
                  >
                    <div
                      onClick={() => handleItemClick(item)}
                      className="flex items-center gap-4 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-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-12 h-12 bg-black flex items-center justify-center text-primary shrink-0 border border-primary/20">
                          <Package size={20} />
                        </div>
                      )}
                      <div className="truncate">
                        <h4 className="text-sm font-normal text-white truncate">{item.name}</h4>
                        <p className="text-[10px] text-secondary font-normal truncate mt-0.5">
                          {item.specs || (item.photo_path || item.image_url ? 'Extract Details via Vision' : 'No Technical Specs')}
                        </p>
                      </div>
                    </div>
                    <div className="text-right shrink-0">
                      <p className={cn(
                        "text-xl font-normal tabular-nums leading-none",
                        item.quantity <= (item.min_quantity || 0) ? "text-rose-500" : "text-primary"
                      )}>
                        {item.quantity}
                      </p>
                      <p className="text-[10px] text-secondary font-normal mt-1">QTY</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>
  );
}

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>
  );
}
