'use client';

import { useState } from 'react';
import { Trash2, Upload, Save } from 'lucide-react';
import { Button } from '@/shared/components/ui/button';
import { Input } from '@/shared/components/ui/input';
import type { SavedSignature, SignatureConfig } from '../types';

interface SavedSignaturesPanelProps {
  saved: SavedSignature[];
  loading: boolean;
  onSave: (label: string, config: SignatureConfig) => Promise<void>;
  onLoad: (config: SignatureConfig) => void;
  onRemove: (id: string) => Promise<void>;
  currentConfig: SignatureConfig;
}

export function SavedSignaturesPanel({
  saved, loading, onSave, onLoad, onRemove, currentConfig,
}: SavedSignaturesPanelProps) {
  const [label, setLabel] = useState('');
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!label.trim()) return;
    setSaving(true);
    await onSave(label.trim(), currentConfig);
    setLabel('');
    setSaving(false);
  };

  return (
    <div className="space-y-3">
      <h3 className="text-sm font-semibold">Semnături salvate</h3>

      <div className="flex gap-2">
        <Input
          placeholder="Nume semnătură..."
          value={label}
          onChange={(e) => setLabel(e.target.value)}
          onKeyDown={(e) => e.key === 'Enter' && handleSave()}
          className="h-8 text-sm"
        />
        <Button size="sm" onClick={handleSave} disabled={saving || !label.trim()}>
          <Save className="mr-1 h-3.5 w-3.5" />
          Salvează
        </Button>
      </div>

      {loading ? (
        <p className="text-xs text-muted-foreground">Se încarcă...</p>
      ) : saved.length === 0 ? (
        <p className="text-xs text-muted-foreground">Nicio semnătură salvată.</p>
      ) : (
        <ul className="space-y-1.5">
          {saved.map((s) => (
            <li key={s.id} className="flex items-center justify-between rounded-md border px-3 py-2">
              <div className="min-w-0 flex-1">
                <span className="text-sm font-medium">{s.label}</span>
                <span className="ml-2 text-xs text-muted-foreground">
                  {s.config.company} &middot; {s.config.name || 'fără nume'}
                </span>
              </div>
              <div className="flex gap-1">
                <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => onLoad(s.config)}>
                  <Upload className="h-3.5 w-3.5" />
                </Button>
                <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => onRemove(s.id)}>
                  <Trash2 className="h-3.5 w-3.5" />
                </Button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
