'use client';

import { useEffect, useRef } from 'react';
import { Zap, X } from 'lucide-react';

export interface QuickReplyTemplate {
  id: string;
  text: string;
  isGlobal: boolean;
  sortOrder: number;
}

interface QuickReplyPickerProps {
  templates: QuickReplyTemplate[];
  onSelect: (text: string) => void;
  onClose: () => void;
}

export function QuickReplyPicker({ templates, onSelect, onClose }: QuickReplyPickerProps) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        onClose();
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [onClose]);

  if (templates.length === 0) {
    return (
      <div
        ref={ref}
        className="absolute bottom-full left-0 mb-2 w-80 rounded-xl border border-slate-200 bg-white p-4 shadow-lg"
      >
        <div className="flex items-center justify-between mb-3">
          <span className="flex items-center gap-1.5 text-sm font-semibold text-slate-700">
            <Zap className="h-4 w-4 text-amber-500" />
            Hızlı Yanıtlar
          </span>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
            <X className="h-4 w-4" />
          </button>
        </div>
        <p className="text-sm text-slate-500">Henüz şablon oluşturulmamış.</p>
      </div>
    );
  }

  return (
    <div
      ref={ref}
      className="absolute bottom-full left-0 mb-2 w-96 rounded-xl border border-slate-200 bg-white shadow-lg"
    >
      <div className="flex items-center justify-between border-b border-slate-100 px-4 py-3">
        <span className="flex items-center gap-1.5 text-sm font-semibold text-slate-700">
          <Zap className="h-4 w-4 text-amber-500" />
          Hızlı Yanıtlar
        </span>
        <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
          <X className="h-4 w-4" />
        </button>
      </div>

      <ul className="max-h-64 overflow-y-auto py-1">
        {templates.map((tpl) => (
          <li key={tpl.id}>
            <button
              onClick={() => {
                onSelect(tpl.text);
                onClose();
              }}
              className="w-full px-4 py-2.5 text-left text-sm text-slate-700 hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
            >
              <div className="flex items-start gap-2">
                <Zap className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-400" />
                <span>{tpl.text}</span>
              </div>
              {tpl.isGlobal && (
                <span className="ml-5 text-[11px] text-slate-400">Genel şablon</span>
              )}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
