'use client';

import { useState } from 'react';
import { Plus, RotateCcw, Trash2, X } from 'lucide-react';
import { Button } from '@/shared/components/ui/button';
import { Textarea } from '@/shared/components/ui/textarea';
import { Label } from '@/shared/components/ui/label';
import { Input } from '@/shared/components/ui/input';
import { cn } from '@/shared/lib/utils';
import { isPresetCategory } from '../services/category-presets';

interface CategoryManagerProps {
  categories: Record<string, { name: string; fieldsText: string }>;
  currentCategory: string;
  onSelectCategory: (name: string) => void;
  onUpdateFields: (name: string, fieldsText: string) => void;
  onAddCategory: (name: string) => void;
  onRemoveCategory: (name: string) => void;
  onResetToPreset: (name: string) => void;
  onClearFields: (name: string) => void;
  baseNamespace: string;
}

function getCategoryNamespace(baseNs: string, category: string): string {
  const safe = category.replace(/\s+/g, '_').replace(/[^A-Za-z0-9_.-]/g, '');
  return baseNs.replace(/\/+$/, '') + '/' + safe;
}

function getCategoryRoot(category: string): string {
  const safe = category.replace(/\s+/g, '_').replace(/[^A-Za-z0-9_.-]/g, '');
  return safe + 'Data';
}

export function CategoryManager({
  categories, currentCategory, onSelectCategory, onUpdateFields,
  onAddCategory, onRemoveCategory, onResetToPreset, onClearFields,
  baseNamespace,
}: CategoryManagerProps) {
  const [newCatName, setNewCatName] = useState('');
  const [showNewCat, setShowNewCat] = useState(false);

  const catNames = Object.keys(categories);
  const currentFields = categories[currentCategory]?.fieldsText ?? '';
  const ns = getCategoryNamespace(baseNamespace, currentCategory);
  const root = getCategoryRoot(currentCategory);

  const handleAddCategory = () => {
    const name = newCatName.trim();
    if (!name || categories[name]) return;
    onAddCategory(name);
    setNewCatName('');
    setShowNewCat(false);
  };

  return (
    <div className="space-y-4">
      {/* Category pills */}
      <div>
        <Label className="mb-1.5 block">Categorii de date</Label>
        <div className="flex flex-wrap gap-1.5">
          {catNames.map((cat) => (
            <button
              key={cat}
              type="button"
              onClick={() => onSelectCategory(cat)}
              className={cn(
                'group inline-flex items-center gap-1 rounded-full border px-3 py-1 text-xs font-medium transition-colors',
                cat === currentCategory
                  ? 'border-primary bg-primary text-primary-foreground'
                  : 'border-border hover:bg-accent'
              )}
            >
              {cat}
              {!isPresetCategory(cat) && (
                <X
                  className="h-3 w-3 opacity-50 group-hover:opacity-100"
                  onClick={(e) => { e.stopPropagation(); onRemoveCategory(cat); }}
                />
              )}
            </button>
          ))}

          {showNewCat ? (
            <div className="flex items-center gap-1">
              <Input
                value={newCatName}
                onChange={(e) => setNewCatName(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleAddCategory()}
                placeholder="Nume categorie..."
                className="h-7 w-36 text-xs"
                autoFocus
              />
              <Button size="icon" variant="ghost" className="h-7 w-7" onClick={handleAddCategory}>
                <Plus className="h-3.5 w-3.5" />
              </Button>
              <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => { setShowNewCat(false); setNewCatName(''); }}>
                <X className="h-3.5 w-3.5" />
              </Button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => setShowNewCat(true)}
              className="inline-flex items-center gap-1 rounded-full border border-dashed px-3 py-1 text-xs text-muted-foreground hover:bg-accent"
            >
              <Plus className="h-3 w-3" /> Adaugă
            </button>
          )}
        </div>
      </div>

      {/* Fields editor */}
      <div>
        <div className="mb-1.5 flex items-center justify-between">
          <Label>Câmpuri — {currentCategory}</Label>
          <div className="flex gap-1">
            {isPresetCategory(currentCategory) && (
              <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => onResetToPreset(currentCategory)}>
                <RotateCcw className="mr-1 h-3 w-3" /> Reset preset
              </Button>
            )}
            <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => onClearFields(currentCategory)}>
              <Trash2 className="mr-1 h-3 w-3" /> Curăță
            </Button>
          </div>
        </div>
        <Textarea
          value={currentFields}
          onChange={(e) => onUpdateFields(currentCategory, e.target.value)}
          rows={8}
          className="font-mono text-xs"
          placeholder="Un câmp pe linie (ex: NumeClient)"
        />
      </div>

      {/* Namespace info */}
      <div className="rounded-md border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
        <p><strong>Namespace:</strong> <code>{ns}</code></p>
        <p><strong>Root element:</strong> <code>&lt;{root}&gt;</code></p>
      </div>
    </div>
  );
}
