import React, { useState, useRef } from 'react';
import {
  X, Save, Plus, Trash2, Image as ImageIcon, Loader, AlertCircle,
  FileText, Type, MousePointer,
} from 'lucide-react';
import api from '../../services/api';

interface TextBlock { id: string; text: string; x: number; y: number; size: number; bold: boolean; color: string; }
interface PageData { id: string; texts: TextBlock[]; imageBase64?: string; imageName?: string; }

function uid() { return Math.random().toString(36).slice(2); }

const defaultPage = (): PageData => ({ id: uid(), texts: [] });
const defaultText = (): TextBlock => ({ id: uid(), text: '', x: 60, y: 80, size: 14, bold: false, color: '#000000' });

// A4 in pdf-lib points: 595.28 × 841.89
const PAGE_W_PT = 595.28;
const PAGE_H_PT = 841.89;
// Preview rendered at this width — large enough for readable text
const PREV_W = 460;
const PREV_H = Math.round(PREV_W * PAGE_H_PT / PAGE_W_PT); // ≈ 651 px
const SCALE = PREV_W / PAGE_W_PT;                           // ≈ 0.773 px/pt

function hexToRgb(hex: string) {
  const n = parseInt(hex.replace('#', ''), 16);
  return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255 };
}

interface PdfCreatorProps { onClose: () => void; onSaved?: () => void; }

export default function PdfCreator({ onClose, onSaved }: PdfCreatorProps) {
  const [title, setTitle] = useState('Novo Documento');
  const [pages, setPages] = useState<PageData[]>([defaultPage()]);
  const [activePage, setActivePage] = useState(0);
  const [activeText, setActiveText] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const imgInputRef = useRef<HTMLInputElement>(null);
  const previewRef = useRef<HTMLDivElement>(null);

  const page = pages[activePage];

  const updatePage = (up: (p: PageData) => PageData) =>
    setPages(prev => prev.map((p, i) => i === activePage ? up(p) : p));

  const addPage = () => {
    setPages(prev => [...prev, defaultPage()]);
    setActivePage(pages.length);
    setActiveText(null);
  };

  const removePage = (idx: number) => {
    if (pages.length === 1) return;
    const next = pages.filter((_, i) => i !== idx);
    setPages(next);
    setActivePage(Math.min(activePage, next.length - 1));
    setActiveText(null);
  };

  const addText = () => {
    const t = defaultText();
    updatePage(p => ({ ...p, texts: [...p.texts, t] }));
    setActiveText(t.id);
  };

  const upd = (tid: string, patch: Partial<TextBlock>) =>
    updatePage(p => ({ ...p, texts: p.texts.map(t => t.id === tid ? { ...t, ...patch } : t) }));

  const removeText = (tid: string) => {
    updatePage(p => ({ ...p, texts: p.texts.filter(t => t.id !== tid) }));
    setActiveText(null);
  };

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => updatePage(p => ({ ...p, imageBase64: reader.result as string, imageName: f.name }));
    reader.readAsDataURL(f);
  };

  const handlePreviewClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!activeText) return;
    const rect = previewRef.current?.getBoundingClientRect();
    if (!rect) return;
    upd(activeText, {
      x: Math.round((e.clientX - rect.left) / SCALE),
      y: Math.round((e.clientY - rect.top) / SCALE),
    });
  };

  const handleSave = async () => {
    setSaving(true); setError(''); setSuccess('');
    try {
      const pagesPayload = pages.map(p => ({
        imageBase64: p.imageBase64,
        texts: p.texts.map(t => ({ ...hexToRgb(t.color), text: t.text, x: t.x, y: t.y, size: t.size, bold: t.bold })),
      }));
      const { data } = await api.post('/pdf/create', { title, pages: pagesPayload, department: '', visibility: 'department' });
      setSuccess(`PDF criado com ${data.pageCount} página(s)!`);
      onSaved?.();
      setTimeout(() => onClose(), 1400);
    } catch (e: any) {
      setError(e.response?.data?.error || 'Erro ao criar PDF');
    } finally { setSaving(false); }
  };

  const inpCls = 'w-full border border-gray-300 rounded-lg px-2 py-1.5 text-xs text-gray-900 bg-white focus:outline-none focus:border-blue-400';

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl w-full max-w-6xl max-h-[92vh] flex flex-col shadow-2xl overflow-hidden">

        {/* Header */}
        <div className="flex items-center gap-3 px-5 py-3 border-b border-gray-200 shrink-0">
          <FileText size={16} className="text-blue-500 shrink-0" />
          <input value={title} onChange={e => setTitle(e.target.value)}
            className="flex-1 bg-transparent text-gray-800 font-semibold text-sm focus:outline-none min-w-0"
            placeholder="Título do documento..." />
          <button onClick={handleSave} disabled={saving}
            className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-500 text-white text-xs rounded-lg hover:bg-blue-600 disabled:opacity-60 font-medium shrink-0">
            {saving ? <Loader size={12} className="animate-spin" /> : <Save size={12} />}
            {saving ? 'Criando...' : 'Criar PDF'}
          </button>
          <button onClick={onClose} className="p-1.5 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-100 shrink-0">
            <X size={16} />
          </button>
        </div>

        {(error || success) && (
          <div className={`mx-4 mt-2 px-3 py-2 rounded-lg text-xs shrink-0 flex items-center gap-2 ${error ? 'bg-red-50 border border-red-200 text-red-600' : 'bg-green-50 border border-green-200 text-green-700'}`}>
            {error && <AlertCircle size={12} />}{error || success}
          </div>
        )}

        <div className="flex flex-1 min-h-0">

          {/* ── Page list ── */}
          <div className="w-24 border-r border-gray-100 bg-gray-50 flex flex-col shrink-0">
            <div className="flex-1 overflow-y-auto p-2 space-y-1.5">
              {pages.map((p, idx) => (
                <div key={p.id} onClick={() => { setActivePage(idx); setActiveText(null); }}
                  className={`relative rounded-lg cursor-pointer border-2 transition-all group ${idx === activePage ? 'border-blue-500 bg-blue-50' : 'border-transparent bg-white hover:border-gray-200'}`}>
                  <div className="h-16 flex flex-col items-center justify-center gap-0.5">
                    <FileText size={16} className={idx === activePage ? 'text-blue-500' : 'text-gray-300'} />
                    <span className="text-[9px] text-gray-500 font-medium">Pág {idx + 1}</span>
                    <span className="text-[8px] text-gray-400">{p.texts.length}T{p.imageBase64 ? '+I' : ''}</span>
                  </div>
                  {pages.length > 1 && (
                    <button onClick={e => { e.stopPropagation(); removePage(idx); }}
                      className="absolute top-0.5 right-0.5 w-3.5 h-3.5 bg-red-100 text-red-500 rounded-full items-center justify-center hidden group-hover:flex text-[9px]">
                      ×
                    </button>
                  )}
                </div>
              ))}
            </div>
            <div className="p-2 border-t border-gray-100">
              <button onClick={addPage}
                className="w-full flex items-center justify-center gap-1 py-1.5 rounded-lg border border-dashed border-gray-300 text-[9px] text-gray-500 hover:border-blue-400 hover:text-blue-500">
                <Plus size={9} /> Página
              </button>
            </div>
          </div>

          {/* ── Controls ── */}
          <div className="w-60 border-r border-gray-100 bg-gray-50 flex flex-col shrink-0 overflow-y-auto">
            <div className="p-3 space-y-4">

              {/* Texts */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-[10px] font-semibold text-gray-500 uppercase tracking-wide">Textos</span>
                  <button onClick={addText}
                    className="flex items-center gap-1 px-2 py-0.5 bg-blue-500 text-white text-[10px] rounded hover:bg-blue-600 font-medium">
                    <Plus size={9} /> Adicionar
                  </button>
                </div>

                {page.texts.length === 0 && (
                  <div className="text-center py-5 text-gray-300">
                    <Type size={20} className="mx-auto mb-1" />
                    <p className="text-[10px]">Nenhum texto ainda</p>
                  </div>
                )}

                <div className="space-y-2">
                  {page.texts.map((t, ti) => {
                    const isAct = activeText === t.id;
                    return (
                      <div key={t.id} onClick={() => setActiveText(t.id)}
                        className={`border rounded-xl p-2.5 space-y-2 cursor-pointer transition-all ${isAct ? 'border-blue-400 bg-blue-50/60' : 'border-gray-200 bg-white hover:border-gray-300'}`}>
                        <div className="flex items-center gap-1.5">
                          <span className="text-[10px] text-gray-500 font-medium">Texto {ti + 1}</span>
                          {isAct && <span className="text-[8px] bg-blue-100 text-blue-600 px-1 py-0.5 rounded-full font-medium">ativo</span>}
                          <button onClick={e => { e.stopPropagation(); removeText(t.id); }}
                            className="ml-auto text-red-300 hover:text-red-500 p-0.5">
                            <Trash2 size={9} />
                          </button>
                        </div>
                        <textarea value={t.text} onChange={e => upd(t.id, { text: e.target.value })}
                          rows={2} placeholder="Conteúdo..."
                          onClick={e => e.stopPropagation()}
                          className={`${inpCls} resize-none`} />
                        <div className="grid grid-cols-2 gap-1.5">
                          <div>
                            <label className="text-[9px] text-gray-400 block mb-0.5">X (pt)</label>
                            <input type="number" value={String(t.x)} onChange={e => upd(t.id, { x: Number(e.target.value) || 0 })} className={inpCls} />
                          </div>
                          <div>
                            <label className="text-[9px] text-gray-400 block mb-0.5">Y (pt)</label>
                            <input type="number" value={String(t.y)} onChange={e => upd(t.id, { y: Number(e.target.value) || 0 })} className={inpCls} />
                          </div>
                          <div>
                            <label className="text-[9px] text-gray-400 block mb-0.5">Tamanho</label>
                            <input type="number" min={6} max={96} value={String(t.size)} onChange={e => upd(t.id, { size: Number(e.target.value) || 12 })} className={inpCls} />
                          </div>
                          <div>
                            <label className="text-[9px] text-gray-400 block mb-0.5">Cor</label>
                            <input type="color" value={t.color} onChange={e => upd(t.id, { color: e.target.value })}
                              className="w-full h-[30px] border border-gray-300 rounded-lg cursor-pointer p-0.5 bg-white" />
                          </div>
                        </div>
                        <label className="flex items-center gap-1.5 cursor-pointer select-none" onClick={e => e.stopPropagation()}>
                          <input type="checkbox" checked={t.bold} onChange={e => upd(t.id, { bold: e.target.checked })} />
                          <span className="text-[10px] text-gray-600">Negrito</span>
                        </label>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Image */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-[10px] font-semibold text-gray-500 uppercase tracking-wide">Imagem</span>
                  {page.imageBase64 && (
                    <button onClick={() => updatePage(p => ({ ...p, imageBase64: undefined, imageName: undefined }))}
                      className="text-[9px] text-red-400 hover:text-red-600">Remover</button>
                  )}
                </div>
                <input ref={imgInputRef} type="file" accept="image/jpeg,image/png" className="sr-only" onChange={handleImageSelect} />
                <button onClick={() => imgInputRef.current?.click()}
                  className="w-full border border-dashed border-gray-300 rounded-xl p-3 text-[10px] text-gray-500 hover:border-blue-400 hover:bg-blue-50 flex items-center justify-center gap-1.5 transition-colors">
                  <ImageIcon size={12} />
                  {page.imageName ? `✓ ${page.imageName}` : 'JPG / PNG'}
                </button>
                {page.imageBase64 && (
                  <img src={page.imageBase64} alt="" className="mt-2 max-h-14 rounded border border-gray-200 mx-auto block" />
                )}
              </div>
            </div>
          </div>

          {/* ── A4 Preview ── */}
          <div className="flex-1 overflow-auto bg-neutral-300 flex flex-col items-center py-6 gap-2">
            {/* Hint */}
            <div className={`flex items-center gap-1.5 text-[10px] px-2.5 py-1 rounded-full font-medium transition-all ${activeText ? 'bg-blue-100 text-blue-700' : 'bg-white/60 text-gray-500'}`}>
              <MousePointer size={10} />
              {activeText ? 'Clique no preview para posicionar o texto' : 'Selecione um texto para posicioná-lo no clique'}
            </div>

            {/* A4 sheet */}
            <div
              ref={previewRef}
              onClick={handlePreviewClick}
              style={{
                width: PREV_W,
                height: PREV_H,
                background: 'white',
                position: 'relative',
                overflow: 'hidden',
                boxShadow: '0 4px 32px rgba(0,0,0,0.22)',
                cursor: activeText ? 'crosshair' : 'default',
                flexShrink: 0,
              }}
            >
              {/* Image — zIndex 1 so texts always render on top */}
              {page.imageBase64 && (
                <img src={page.imageBase64} alt=""
                  style={{
                    position: 'absolute',
                    zIndex: 1,
                    left: 50 * SCALE,
                    top: 50 * SCALE,
                    maxWidth: (PAGE_W_PT - 100) * SCALE,
                    maxHeight: (PAGE_H_PT - 200) * SCALE,
                  }}
                />
              )}

              {/* Texts — zIndex 2 ensures they render above the image */}
              {page.texts.map(t => (
                <div key={t.id} style={{
                  position: 'absolute',
                  zIndex: 2,
                  left: t.x * SCALE,
                  top: t.y * SCALE,
                  fontSize: Math.max(t.size * SCALE, 8),
                  fontWeight: t.bold ? 'bold' : 'normal',
                  color: t.color || '#000000',
                  maxWidth: (PAGE_W_PT - t.x) * SCALE,
                  wordBreak: 'break-word',
                  whiteSpace: 'pre-wrap',
                  lineHeight: 1.35,
                  outline: activeText === t.id ? '1.5px solid #3b82f6' : 'none',
                  outlineOffset: 1,
                  fontFamily: 'Helvetica, Arial, sans-serif',
                  pointerEvents: 'none',
                  /* White drop-shadow so text is readable on any background */
                  textShadow: t.color === '#ffffff' || t.color === '#fff'
                    ? '0 0 3px #000'
                    : '0 0 3px rgba(255,255,255,0.8)',
                }}>
                  {t.text || <span style={{ color: '#d1d5db', fontSize: 9, fontStyle: 'italic', fontWeight: 'normal' }}>texto {page.texts.indexOf(t) + 1}</span>}
                </div>
              ))}

              {page.texts.length === 0 && !page.imageBase64 && (
                <p style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', fontSize: 10, color: '#d1d5db', pointerEvents: 'none', whiteSpace: 'nowrap' }}>
                  Página em branco
                </p>
              )}
            </div>

            <p style={{ fontSize: 9, color: '#9ca3af' }}>Preview · A4 em escala</p>
          </div>

        </div>
      </div>
    </div>
  );
}
