import React, { useEffect, useState } from 'react';
import { Copy, Send } from 'lucide-react';
import { publishMessage } from '../utils/api';

interface PublishPanelProps {
  draft: { topic: string; payload: string };
  onDraftChange: (draft: { topic: string; payload: string }) => void;
  onPasteTopic: () => void;
  onPastePayload: () => void;
}

export const PublishPanel: React.FC<PublishPanelProps> = ({ draft, onDraftChange, onPasteTopic, onPastePayload }) => {
  const [topic, setTopic] = useState(draft.topic);
  const [payload, setPayload] = useState(draft.payload);
  const [qos, setQos] = useState(0);
  const [retained, setRetained] = useState(false);
  const [status, setStatus] = useState<string | null>(null);

  useEffect(() => {
    setTopic(draft.topic);
    setPayload(draft.payload);
  }, [draft.payload, draft.topic]);

  const handlePublish = async () => {
    if (!topic) {
      setStatus('Topic requis.');
      return;
    }
    try {
      await publishMessage({ topic, payload, qos, retained });
      setStatus('Message publié.');
    } catch (err) {
      setStatus('Erreur de publication.');
    }
  };

  const copyWithFallback = async (text: string) => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      await navigator.clipboard.writeText(text);
      return true;
    }
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.setAttribute('readonly', 'true');
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.select();
    const ok = document.execCommand('copy');
    document.body.removeChild(textarea);
    return ok;
  };

  const handleCopyPayload = async () => {
    if (!payload) {
      setStatus('Payload vide.');
      return;
    }
    try {
      const ok = await copyWithFallback(payload);
      setStatus(ok ? 'Payload copié.' : 'Copie impossible.');
    } catch (err) {
      setStatus('Copie impossible.');
    }
  };

  const handleCopyTopic = async () => {
    if (!topic) {
      setStatus('Topic vide.');
      return;
    }
    try {
      const ok = await copyWithFallback(topic);
      setStatus(ok ? 'Topic copié.' : 'Copie impossible.');
    } catch (err) {
      setStatus('Copie impossible.');
    }
  };

  useEffect(() => {
    onDraftChange({ topic, payload });
  }, [onDraftChange, payload, topic]);

  return (
    <div className="flex flex-col h-full bg-[color:var(--bg-main)] ui-font">
      <div className="p-4 border-b border-[color:var(--border)] bg-[color:var(--bg-panel)]">
        <h2 className="font-semibold">Publier un message</h2>
      </div>
      <div className="flex-1 overflow-auto p-4 space-y-4 custom-scrollbar">
        <div>
          <label className="opacity-70">Topic</label>
          <div className="flex items-center gap-2">
            <div className="flex flex-col gap-2">
              <button
                type="button"
                onClick={onPasteTopic}
                className="w-8 h-8 rounded border border-[color:var(--border)] flex items-center justify-center hover:border-[color:var(--accent-green)]"
                title="Insérer le topic sélectionné"
              >
                -&gt;
              </button>
            </div>
            <div className="relative w-full">
              <input
                value={topic}
                onChange={(e) => setTopic(e.target.value)}
                className="w-full bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 pr-12"
                placeholder="ex: devices/esp32/cmd"
              />
              <button
                type="button"
                onClick={handleCopyTopic}
                className="absolute top-1/2 right-3 -translate-y-1/2 p-1.5 rounded border border-[color:var(--border)] hover:border-[color:var(--accent-green)]"
                title="Copier le topic"
              >
                <Copy size={14} />
              </button>
            </div>
          </div>
        </div>
        <div>
          <label className="opacity-70">Payload</label>
          <div className="flex items-start gap-2">
            <div className="flex flex-col gap-2">
              <button
                type="button"
                onClick={onPastePayload}
                className="w-8 h-8 rounded border border-[color:var(--border)] flex items-center justify-center hover:border-[color:var(--accent-green)]"
                title="Insérer le payload sélectionné"
              >
                -&gt;
              </button>
            </div>
            <div className="relative w-full">
              <textarea
                value={payload}
                onChange={(e) => setPayload(e.target.value)}
                className="w-full bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 h-32 pr-12 payload-font font-mono"
                placeholder='{"action":"on"}'
              />
              <button
                type="button"
                onClick={handleCopyPayload}
                className="absolute top-2 right-3 p-1.5 rounded border border-[color:var(--border)] hover:border-[color:var(--accent-green)]"
                title="Copier le payload"
              >
                <Copy size={14} />
              </button>
            </div>
          </div>
        </div>
        <div className="flex gap-4">
          <div>
            <label className="opacity-70">QoS</label>
            <select
              value={qos}
              onChange={(e) => setQos(Number(e.target.value))}
              className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2"
            >
              <option value={0}>0</option>
              <option value={1}>1</option>
              <option value={2}>2</option>
            </select>
          </div>
          <label className="flex items-center gap-2 mt-6">
            <input
              type="checkbox"
              checked={retained}
              onChange={(e) => setRetained(e.target.checked)}
            />
            Retained
          </label>
        </div>
        <button
          onClick={handlePublish}
          className="flex items-center gap-2 px-4 py-2 rounded bg-[color:var(--accent-green)] text-black font-semibold"
        >
          <Send size={14} /> Publier
        </button>
        {status && <div className="opacity-70">{status}</div>}
      </div>
    </div>
  );
};
