/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import { 
  Search, ChevronDown, Check, PlusCircle, Sparkles, X, 
  Database
} from 'lucide-react';
import { ReferenceDatabase } from '../types';

interface VariablesSidebarProps {
  isOpen: boolean;
  onClose: () => void;
  insertHTMLAtCursor: (html: string) => void;
  getReferenceOptionsForKey: (key: string) => any[];
  databases: ReferenceDatabase[];
  editorRef: React.RefObject<HTMLDivElement | null>;
}

export default function VariablesSidebar({
  isOpen,
  onClose,
  insertHTMLAtCursor,
  getReferenceOptionsForKey,
  databases = [],
  editorRef,
}: VariablesSidebarProps) {
  const [sidebarSearch, setSidebarSearch] = useState('');
  const [activeCategory, setActiveCategory] = useState('Semua');
  const [lastInsertedVar, setLastInsertedVar] = useState<string | null>(null);
  const [activeDropdownVar, setActiveDropdownVar] = useState<string | null>(null);

  if (!isOpen) return null;

  return (
    <aside className="w-80 border-l border-slate-200 bg-slate-50 flex flex-col shrink-0 overflow-hidden print:hidden select-none animate-in slide-in-from-right duration-200">
      {/* Sidebar header */}
      <div className="p-4 border-b border-slate-200 bg-white flex items-center justify-between shrink-0 shadow-sm shadow-slate-100">
        <div className="flex items-center space-x-2">
          <Sparkles className="w-4 h-4 text-blue-600 animate-pulse" />
          <h3 className="text-xs font-bold text-slate-800 uppercase tracking-wider">Koleksi Variabel</h3>
        </div>
        <button
          type="button"
          onClick={onClose}
          className="p-1 hover:bg-slate-100 rounded text-slate-400 hover:text-slate-600 transition-all cursor-pointer"
          title="Sembunyikan Panel"
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* Search Input filter */}
      <div className="p-3 bg-white border-b border-slate-200 shrink-0">
        <div className="relative">
          <input
            type="text"
            placeholder="Cari kolom variabel..."
            value={sidebarSearch}
            onChange={(e) => setSidebarSearch(e.target.value)}
            className="w-full bg-slate-50 border border-slate-200 hover:border-slate-350 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 rounded-lg pl-8 pr-8 py-1.5 text-xs outline-none transition-all text-slate-700 font-medium"
          />
          <Search className="w-3.5 h-3.5 absolute left-2.5 top-2.5 text-slate-400 pointer-events-none" />
          {sidebarSearch && (
            <button
              type="button"
              onClick={() => setSidebarSearch('')}
              className="absolute right-2.5 top-2.5 text-slate-400 hover:text-slate-600 p-0.5 rounded cursor-pointer"
            >
              <X className="w-3 h-3" />
            </button>
          )}
        </div>
      </div>

      {/* Category Header Switcher Tabs */}
      <div className="px-3 py-1.5 bg-slate-100/50 border-b border-slate-150 flex gap-1 overflow-x-auto scrollbar-none shrink-0 scroll-smooth">
        {['Semua', ...databases.map(db => db.name)].map((cat) => {
          const isActive = activeCategory === cat;
          return (
            <button
              key={cat}
              type="button"
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => setActiveCategory(cat)}
              className={`px-2 py-1 rounded text-[10px] font-bold shrink-0 transition-all cursor-pointer whitespace-nowrap ${
                isActive
                  ? 'bg-blue-600 text-white shadow-sm shadow-blue-500/10'
                  : 'bg-white text-slate-500 hover:text-slate-800 border border-slate-200 hover:border-slate-300'
              }`}
            >
              {cat.length > 20 ? cat.slice(0, 15) + '...' : cat}
            </button>
          );
        })}
      </div>

      {/* Scrollable Variables Library list */}
      <div className="flex-1 overflow-y-auto p-3 space-y-4 max-h-[calc(100vh-390px)]">
        {(() => {
          // Dynamic databases filter logic
          const matchedDatabases = databases.map(db => {
            const filteredCols = db.columns.filter(col => 
              col.toLowerCase().includes(sidebarSearch.toLowerCase())
            );
            return { ...db, columns: filteredCols };
          }).filter(db => db.columns.length > 0);

          // Apply active category tab filter
          const displayedDatabases = activeCategory === 'Semua'
            ? matchedDatabases
            : matchedDatabases.filter(db => db.name === activeCategory);

          if (displayedDatabases.length === 0) {
            return (
              <div className="text-center py-10 px-4 bg-white border border-slate-200 rounded-xl">
                <p className="text-xs text-slate-400 font-bold mr-1">Nama variabel tidak ditemukan</p>
                <p className="text-[10px] text-slate-400 mt-1 leading-relaxed">Cek kembali kata kunci pencarian Anda atau tambahkan kolom baru di Data Referensi.</p>
              </div>
            );
          }

          return displayedDatabases.map((db) => (
            <div key={db.id} className="space-y-1.5">
              <div className="flex items-center space-x-1.5 px-1">
                <Database className="w-3 h-3 text-slate-400" />
                <h4 className="text-[10px] font-bold text-slate-400 uppercase tracking-widest font-sans">
                  {db.name}
                </h4>
              </div>
              <div className="space-y-1.5">
                {db.columns.map((col) => {
                  const tagText = `(${col})`;
                  const isInserted = lastInsertedVar === col;
                  const isDropdownOpen = activeDropdownVar === `${db.id}-${col}`;

                  // Values option selector matching this column
                  const colValues = db.rows
                    .map(r => r[col])
                    .filter(Boolean)
                    .filter((v, i, self) => self.indexOf(v) === i); // Distinct
                  
                  const hasDropdown = colValues.length > 0;

                  return (
                    <div 
                      key={col} 
                      className={`border rounded-lg bg-white overflow-hidden transition-all shadow-xs ${
                        isInserted 
                          ? 'border-emerald-300 bg-emerald-55/5' 
                          : isDropdownOpen 
                            ? 'border-blue-400 bg-blue-50/5' 
                            : 'border-slate-200 hover:border-blue-200'
                      }`}
                    >
                      <div className="flex items-stretch justify-between">
                        <button
                          type="button"
                          onMouseDown={(e) => e.preventDefault()}
                          onClick={() => {
                            insertHTMLAtCursor(tagText);
                            setLastInsertedVar(col);
                            setTimeout(() => setLastInsertedVar(null), 1250);
                          }}
                          className="flex-1 text-left p-2.5 transition-colors hover:bg-slate-50 min-w-0"
                          title={`Klik untuk menyisipkan variabel placeholder ${tagText}`}
                        >
                          <span className="text-[11px] font-bold text-slate-700 truncate block leading-none">
                            {col}
                          </span>
                          <span className="text-[9.5px] text-slate-400 block mt-1.5 leading-tight font-medium font-mono truncate">
                            Tag: {tagText}
                          </span>
                        </button>

                        <div className="flex items-stretch border-l border-slate-100 shrink-0">
                          {isInserted ? (
                            <div className="px-2.5 flex items-center bg-emerald-50">
                              <Check className="w-3.5 h-3.5 text-emerald-600 animate-bounce" />
                            </div>
                          ) : hasDropdown ? (
                            <button
                              type="button"
                              onMouseDown={(e) => e.preventDefault()}
                              onClick={() => {
                                setActiveDropdownVar(isDropdownOpen ? null : `${db.id}-${col}`);
                              }}
                              className={`px-2.5 flex items-center hover:bg-blue-50 hover:text-blue-600 transition-all ${
                                isDropdownOpen ? 'bg-blue-50 text-blue-650' : 'text-slate-400'
                              }`}
                              title="Pilih Nilai Cepat dari Database"
                            >
                              <ChevronDown className={`w-3.5 h-3.5 transition-transform duration-200 ${isDropdownOpen ? 'rotate-180' : ''}`} />
                            </button>
                          ) : (
                            <button
                              type="button"
                              onMouseDown={(e) => e.preventDefault()}
                              onClick={() => {
                                insertHTMLAtCursor(tagText);
                                setLastInsertedVar(col);
                                setTimeout(() => setLastInsertedVar(null), 1250);
                              }}
                              className="px-2.5 flex items-center text-slate-300 hover:text-blue-550 transition-colors"
                            >
                              <PlusCircle className="w-3.5 h-3.5" />
                            </button>
                          )}
                        </div>
                      </div>

                      {/* Expanded rows lookup values for quick manual injection */}
                      {hasDropdown && isDropdownOpen && (
                        <div className="bg-slate-50 border-t border-slate-100 p-2 space-y-1.5">
                          <div className="text-[9px] font-bold text-slate-400 tracking-wider uppercase px-1">
                            Pilih Nilai Database:
                          </div>
                          <div className="flex flex-col gap-1 max-h-[160px] overflow-y-auto">
                            {db.rows.map((row, rIdx) => {
                              const cellVal = row[col];
                              if (!cellVal) return null;
                              return (
                                <button 
                                  key={row.id || rIdx}
                                  type="button"
                                  onMouseDown={(e) => e.preventDefault()}
                                  onClick={() => {
                                    insertHTMLAtCursor(cellVal);
                                    setLastInsertedVar(col);
                                    setActiveDropdownVar(null);
                                    setTimeout(() => setLastInsertedVar(null), 1250);
                                  }}
                                  className="w-full flex flex-col p-2 bg-white border border-slate-200 rounded hover:border-blue-450 hover:bg-blue-50/5 transition-all text-left cursor-pointer"
                                  title={`Nilai: "${cellVal}" (${col})`}
                                >
                                  <div className="text-[10px] font-bold text-slate-800 line-clamp-1 leading-tight">
                                    {cellVal}
                                  </div>
                                  <div className="text-[8.5px] text-slate-400 font-semibold truncate mt-1">
                                    Milik: {row[db.columns[0]] || 'Rekor ini'}
                                  </div>
                                </button>
                              );
                            })}
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ));
        })()}
      </div>
    </aside>
  );
}
