import React, { useState, useEffect } from 'react';
import { X, Save, FileText, Camera, X as XIcon, Share2, MessageSquare, MessageCircle, Copy } from 'lucide-react';
import { useOrderPhotos } from './useOrderPhotos';
import { useOrderComments } from './useOrderComments';
import { pdf } from '@react-pdf/renderer';
import { supabase } from '../../lib/supabase';
import { useAuth } from '../auth/useAuth';
import { usePricing } from '../../hooks/usePricing';
import { useIsMobile } from '../../hooks/useIsMobile';
import { InvoicePDF } from './InvoicePDF';

const STATUSES = ['новая', 'замер', 'согласование', 'монтаж', 'закрыт'];

const TEMPLATES = [
  {
    id: 'confirm',
    label: 'Подтверждение визита',
    text: (f) => {
      const date = f.scheduled_at
        ? new Date(f.scheduled_at).toLocaleString('ru-RU', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' })
        : '[дата не указана]';
      return `Здравствуйте, ${f.name || '[имя]'}! Подтверждаем ваш визит ${date}${f.address ? ` по адресу: ${f.address}` : ''}. Ждём вас!`;
    },
  },
  {
    id: 'reminder',
    label: 'Напоминание (за день)',
    text: (f) => {
      const date = f.scheduled_at
        ? new Date(f.scheduled_at).toLocaleString('ru-RU', { day: 'numeric', month: 'long', hour: '2-digit', minute: '2-digit' })
        : '[дата не указана]';
      return `${f.name || 'Клиент'}, напоминаем о визите завтра в ${date.split(',')[1]?.trim() || '[время]'}${f.address ? `, адрес: ${f.address}` : ''}. До встречи!`;
    },
  },
  {
    id: 'received',
    label: 'Заявка получена',
    text: (f) => `Здравствуйте, ${f.name || '[имя]'}! Ваша заявка принята. Менеджер свяжется с вами в ближайшее время для уточнения деталей.`,
  },
  {
    id: 'done',
    label: 'Работы завершены',
    text: (f) => {
      const cost = f.final_cost ? `Итоговая стоимость: ${Number(f.final_cost).toLocaleString('ru-RU')} ₽.` : '';
      return `${f.name || 'Клиент'}, работы по бронированию стёкол завершены. ${cost} Спасибо за доверие!`;
    },
  },
];
const OBJECT_TYPES = [
  { value: 'industrial', label: 'Промышленный объект' },
  { value: 'commercial', label: 'Коммерческая штаб-квартира' },
  { value: 'infrastructure', label: 'Критическая инфраструктура' },
  { value: 'residential', label: 'Частная резиденция' },
  { value: 'other', label: 'Другое' },
];

const inputStyle = {
  width: '100%', padding: '10px 12px',
  background: 'var(--bg-lighter)',
  border: '1.5px solid var(--border-light)',
  borderRadius: '6px',
  color: 'var(--text-main)', fontSize: '0.92rem',
  outline: 'none', fontFamily: 'var(--font-body)',
  boxSizing: 'border-box',
};

const labelStyle = {
  display: 'block', marginBottom: '5px',
  fontSize: '0.75rem', fontWeight: 700,
  color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.4px',
};

const OrderModal = ({ order, onClose, onSaved, mode = 'edit' }) => {
  const { session } = useAuth();
  const { prices } = usePricing();
  const isMobile = useIsMobile();
  const [form, setForm] = useState({
    name: order?.name || '',
    phone: order?.phone || '',
    object_type: order?.object_type || '',
    area_sqm: order?.area_sqm ?? '',
    film_thickness: order?.film_thickness ?? 200,
    final_cost: order?.final_cost ?? '',
    notes: order?.notes || '',
    assigned_to: order?.assigned_to || '',
    status: order?.status || 'новая',
    telegram_username: order?.telegram_username || '',
    max_username: order?.max_username || '',
    address: order?.address || '',
    scheduled_at: order?.scheduled_at ? new Date(order.scheduled_at).toISOString().slice(0, 16) : '',
  });
  const [events, setEvents] = useState([]);
  const { photos, uploading, uploadPhotos, deletePhoto } = useOrderPhotos(mode === 'edit' ? order?.id : null);
  const { comments, loading: commentsLoading, addComment } = useOrderComments(mode === 'edit' ? order?.id : null);
  const [saving, setSaving] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState(false);
  const [templatesOpen, setTemplatesOpen] = useState(false);
  const [copiedTpl, setCopiedTpl] = useState(null);
  const [commentText, setCommentText] = useState('');

  useEffect(() => {
    if (order?.id) {
      supabase
        .from('order_events')
        .select('*')
        .eq('order_id', order.id)
        .order('created_at', { ascending: false })
        .then(({ data }) => setEvents(data || []));
    }
  }, [order?.id]);

  useEffect(() => {
    const area = Number(form.area_sqm);
    if (!area || isNaN(area)) return;
    const price = prices[form.film_thickness] ?? prices[200];
    setForm((prev) => ({ ...prev, final_cost: Math.round(area * price) }));
  }, [form.area_sqm, form.film_thickness, prices]);

  const modalRef = React.useRef(null);

  useEffect(() => {
    const handleKey = (e) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKey);
    modalRef.current?.focus();
    return () => document.removeEventListener('keydown', handleKey);
  }, [onClose]);

  const set = (e) => setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));

  const toPayload = (f) => ({
    ...f,
    area_sqm: f.area_sqm === '' ? null : Number(f.area_sqm),
    final_cost: f.final_cost === '' ? null : Number(f.final_cost),
    scheduled_at: f.scheduled_at === '' ? null : new Date(f.scheduled_at).toISOString(),
  });

  const handleCopyTemplate = (tpl) => {
    const text = tpl.text(form);
    navigator.clipboard.writeText(text).then(() => {
      setCopiedTpl(tpl.id);
      setTimeout(() => setCopiedTpl(null), 2000);
    });
  };

  const handleShare = () => {
    const url = `${window.location.origin}/track/${order.public_token}`;
    navigator.clipboard.writeText(url).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const handleAddComment = async () => {
    if (!commentText.trim()) return;
    await addComment(session?.user?.email || 'Аноним', commentText.trim());
    setCommentText('');
  };

  const handleDuplicate = async () => {
    const { name, phone, object_type, area_sqm, film_thickness, final_cost, notes, assigned_to, address, telegram_username, max_username } = form;
    const { error } = await supabase.from('orders').insert({
      name, phone, object_type,
      area_sqm: area_sqm === '' ? null : Number(area_sqm),
      film_thickness,
      final_cost: final_cost === '' ? null : Number(final_cost),
      notes, assigned_to, address, telegram_username, max_username,
      status: 'новая', source: 'manual',
    });
    if (!error) {
      onSaved();
    } else {
      setError(error.message);
    }
  };

  const handleSave = async () => {
    if (!form.name.trim() || !form.phone.trim()) {
      setError('Имя и телефон обязательны');
      return;
    }
    setSaving(true);
    setError('');
    const userEmail = session?.user?.email;

    if (mode === 'create') {
      const { error } = await supabase
        .from('orders')
        .insert({ ...toPayload(form), source: 'manual' });
      if (error) { setError(error.message); setSaving(false); return; }
    } else {
      const statusChanged = form.status !== order.status;
      const updates = { ...toPayload(form) };
      if (statusChanged) {
        if (form.status === 'закрыт') {
          updates.closed_at = new Date().toISOString();
        } else if (order.status === 'закрыт') {
          updates.closed_at = null;
        }
      }

      const { error } = await supabase.from('orders').update(updates).eq('id', order.id);
      if (error) { setError(error.message); setSaving(false); return; }

      const { error: evtErr } = await supabase.from('order_events').insert({
        order_id: order.id,
        created_by: userEmail,
        event_type: statusChanged ? 'status_change' : 'edit',
        description: statusChanged
          ? `Статус изменён: ${order.status} → ${form.status}`
          : 'Данные заказа обновлены',
      });
      if (evtErr) console.error('Failed to log order event:', evtErr);

      if (statusChanged) {
        const message =
          `📋 Статус заказа изменён\n\n` +
          `Клиент: ${form.name}\n` +
          `Телефон: ${form.phone}\n` +
          (form.telegram_username ? `Telegram: ${form.telegram_username}\n` : '') +
          (form.max_username ? `Max: ${form.max_username}\n` : '') +
          `Статус: ${order.status} → ${form.status}\n` +
          (form.address ? `Адрес: ${form.address}\n` : '') +
          (form.final_cost ? `Сумма: ${Number(form.final_cost).toLocaleString('ru-RU')} ₽\n` : '');

        fetch(
          `https://api.telegram.org/bot${import.meta.env.VITE_TG_BOT_TOKEN}/sendMessage`,
          {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              chat_id: import.meta.env.VITE_TG_CHAT_ID,
              text: message,
              parse_mode: 'HTML',
            }),
          }
        ).catch(() => {});
      }
    }
    setSaving(false);
    onSaved?.();
    onClose();
  };

  const handleDownloadPDF = async () => {
    setDownloading(true);
    const blob = await pdf(<InvoicePDF order={{ ...order, ...form }} />).toBlob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `smeta-${order.name?.replace(/\s+/g, '-') || order.id}.pdf`;
    a.click();
    URL.revokeObjectURL(url);
    setDownloading(false);
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label={mode === 'create' ? 'Новая заявка' : `Заявка: ${order?.name}`}
      style={{
        position: 'fixed', inset: 0,
        background: 'rgba(15, 23, 42, 0.55)',
        display: 'flex', alignItems: isMobile ? 'flex-end' : 'center', justifyContent: 'center',
        zIndex: 1000, backdropFilter: 'blur(4px)',
      }}
      onClick={onClose}
    >
      <div
        ref={modalRef}
        tabIndex={-1}
        className="glass-panel"
        style={{
          width: '100%',
          maxWidth: isMobile ? '100%' : '620px',
          maxHeight: isMobile ? '92vh' : '90vh',
          overflow: 'auto',
          padding: isMobile ? '20px 16px' : '30px',
          margin: isMobile ? '0' : '20px',
          borderRadius: isMobile ? '20px 20px 0 0' : '16px',
          alignSelf: isMobile ? 'flex-end' : 'center',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '22px' }}>
          <h2 style={{ fontFamily: 'var(--font-heading)', fontSize: '1.2rem', fontWeight: 800 }}>
            {mode === 'create' ? 'Новая заявка' : order?.name}
          </h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            {mode === 'edit' && (
              <button
                type="button"
                onClick={handleDuplicate}
                title="Создать копию заявки"
                style={{
                  background: 'none', border: '1.5px solid var(--border-light)',
                  borderRadius: '6px', padding: '5px 10px',
                  cursor: 'pointer', color: 'var(--text-muted)',
                  display: 'inline-flex', alignItems: 'center', gap: '5px',
                  fontSize: '0.78rem', fontFamily: 'var(--font-heading)',
                }}
              >
                <Copy size={13} />
                Дублировать
              </button>
            )}
            {mode === 'edit' && order?.public_token && (
              <button
                onClick={handleShare}
                aria-label="Поделиться ссылкой на заявку"
                title="Скопировать ссылку для клиента"
                style={{
                  display: 'flex', alignItems: 'center', gap: '5px',
                  background: copied ? '#10b981' : 'var(--bg-lighter)',
                  border: '1.5px solid var(--border-light)',
                  borderRadius: '7px',
                  padding: '5px 10px',
                  cursor: 'pointer',
                  fontSize: '0.78rem',
                  fontWeight: 600,
                  color: copied ? '#fff' : 'var(--text-muted)',
                  transition: 'background 0.2s, color 0.2s',
                }}
              >
                <Share2 size={13} />
                {copied ? 'Скопировано!' : 'Поделиться'}
              </button>
            )}
            <button
              onClick={onClose}
              aria-label="Закрыть"
              style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)' }}
            >
              <X size={20} />
            </button>
          </div>
        </div>

        {/* Fields */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
          <div>
            <label htmlFor="modal-name" style={labelStyle}>ФИО / Организация *</label>
            <input id="modal-name" name="name" value={form.name} onChange={set} style={inputStyle} />
          </div>
          <div>
            <label htmlFor="modal-phone" style={labelStyle}>Телефон *</label>
            <input id="modal-phone" name="phone" value={form.phone} onChange={set} style={inputStyle} />
          </div>
          <div>
            <label htmlFor="modal-object-type" style={labelStyle}>Тип объекта</label>
            <select id="modal-object-type" name="object_type" value={form.object_type} onChange={set} style={{ ...inputStyle, cursor: 'pointer' }}>
              <option value="">Не выбрано</option>
              {OBJECT_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
            </select>
          </div>
          <div>
            <label htmlFor="modal-status" style={labelStyle}>Статус</label>
            <select id="modal-status" name="status" value={form.status} onChange={set} style={{ ...inputStyle, cursor: 'pointer' }}>
              {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
            </select>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label htmlFor="modal-scheduled" style={labelStyle}>Дата визита</label>
            <input
              id="modal-scheduled"
              type="datetime-local"
              name="scheduled_at"
              value={form.scheduled_at}
              onChange={(e) => setForm((prev) => ({ ...prev, scheduled_at: e.target.value }))}
              style={inputStyle}
            />
          </div>
          <div>
            <label htmlFor="modal-area" style={labelStyle}>Площадь (м²)</label>
            <input id="modal-area" type="number" name="area_sqm" value={form.area_sqm} onChange={set} style={inputStyle} />
          </div>
          <div>
            <label htmlFor="modal-thickness" style={labelStyle}>Толщина плёнки</label>
            <select id="modal-thickness" name="film_thickness" value={form.film_thickness} onChange={(e) => setForm((prev) => ({ ...prev, film_thickness: Number(e.target.value) }))} style={{ ...inputStyle, cursor: 'pointer' }}>
              <option value={200}>200 микрон</option>
              <option value={300}>300 микрон</option>
            </select>
          </div>
          <div>
            <label htmlFor="modal-final" style={labelStyle}>Итоговая стоимость (₽)</label>
            <input id="modal-final" type="number" name="final_cost" value={form.final_cost} onChange={set} style={inputStyle} />
            <p style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '3px' }}>Рассчитывается автоматически</p>
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label htmlFor="modal-assigned" style={labelStyle}>Ответственный (email)</label>
            <input id="modal-assigned" name="assigned_to" value={form.assigned_to} onChange={set} style={inputStyle} placeholder="manager@company.com" />
          </div>
          <div>
            <label htmlFor="modal-telegram" style={labelStyle}>Telegram</label>
            <input id="modal-telegram" name="telegram_username" value={form.telegram_username} onChange={set} style={inputStyle} placeholder="@username" />
          </div>
          <div>
            <label htmlFor="modal-max" style={labelStyle}>Max</label>
            <input id="modal-max" name="max_username" value={form.max_username} onChange={set} style={inputStyle} placeholder="@username" />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label htmlFor="modal-address" style={labelStyle}>Адрес</label>
            <textarea id="modal-address" name="address" value={form.address} onChange={set} style={{ ...inputStyle, height: '60px', resize: 'vertical' }} placeholder="Улица, дом, квартира" />
          </div>
        </div>

        <div style={{ marginTop: '14px' }}>
          <label htmlFor="modal-notes" style={labelStyle}>Заметки</label>
          <textarea id="modal-notes" name="notes" value={form.notes} onChange={set} style={{ ...inputStyle, height: '72px', resize: 'vertical' }} />
        </div>

        {mode === 'edit' && (
          <div style={{ marginTop: '14px' }}>
            <button
              type="button"
              onClick={() => setTemplatesOpen((v) => !v)}
              style={{
                display: 'flex', alignItems: 'center', gap: '6px',
                background: 'none', border: 'none', cursor: 'pointer',
                fontSize: '0.82rem', fontWeight: 700, color: 'var(--text-muted)',
                padding: '4px 0', fontFamily: 'var(--font-heading)',
                textTransform: 'uppercase', letterSpacing: '0.4px',
              }}
            >
              <MessageSquare size={14} />
              Шаблоны сообщений
              <span style={{ marginLeft: '2px', fontSize: '0.7rem' }}>{templatesOpen ? '▲' : '▼'}</span>
            </button>

            {templatesOpen && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '10px' }}>
                {TEMPLATES.map((tpl) => (
                  <div
                    key={tpl.id}
                    style={{
                      background: 'var(--bg-lighter)', border: '1px solid var(--border-light)',
                      borderRadius: '8px', padding: '12px',
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: '8px' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: '0.75rem', fontWeight: 700, color: 'var(--text-muted)', marginBottom: '4px', textTransform: 'uppercase', letterSpacing: '0.3px' }}>
                          {tpl.label}
                        </div>
                        <div style={{ fontSize: '0.83rem', color: 'var(--text-main)', lineHeight: 1.5 }}>
                          {tpl.text(form)}
                        </div>
                      </div>
                      <button
                        type="button"
                        onClick={() => handleCopyTemplate(tpl)}
                        style={{
                          flexShrink: 0, padding: '6px 12px',
                          background: copiedTpl === tpl.id ? '#10b981' : '#4361EE',
                          color: '#fff', border: 'none', borderRadius: '6px',
                          fontSize: '0.78rem', fontWeight: 700, cursor: 'pointer',
                          fontFamily: 'var(--font-heading)',
                          transition: 'background 0.15s',
                        }}
                      >
                        {copiedTpl === tpl.id ? 'Скопировано!' : 'Копировать'}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {mode === 'edit' && (
          <div style={{ marginTop: '24px', borderTop: '1px solid var(--border-light)', paddingTop: '20px' }}>
            <h3 style={{ fontFamily: 'var(--font-heading)', fontSize: '0.9rem', fontWeight: 700, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
              <MessageCircle size={16} color="var(--accent-blue)" />
              Комментарии {comments.length > 0 && <span style={{ fontSize: '0.75rem', background: '#EEF2FF', color: '#4361EE', padding: '1px 7px', borderRadius: '10px', fontWeight: 700 }}>{comments.length}</span>}
            </h3>

            {/* Comment list */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '10px', marginBottom: '14px' }}>
              {comments.length === 0 && (
                <p style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>Комментариев пока нет</p>
              )}
              {comments.map((c) => (
                <div key={c.id} style={{
                  background: 'var(--bg-lighter)', border: '1px solid var(--border-light)',
                  borderRadius: '8px', padding: '10px 14px',
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                    <span style={{ fontSize: '0.78rem', fontWeight: 700, color: '#4361EE' }}>{c.author}</span>
                    <span style={{ fontSize: '0.72rem', color: 'var(--text-muted)' }}>
                      {new Date(c.created_at).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                    </span>
                  </div>
                  <p style={{ fontSize: '0.85rem', color: 'var(--text-main)', lineHeight: 1.5, margin: 0 }}>{c.body}</p>
                </div>
              ))}
            </div>

            {/* Add comment */}
            <div style={{ display: 'flex', gap: '8px' }}>
              <input
                value={commentText}
                onChange={(e) => setCommentText(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleAddComment()}
                placeholder="Добавить комментарий... (Enter для отправки)"
                style={{ ...inputStyle, flex: 1 }}
                disabled={commentsLoading}
              />
              <button
                type="button"
                onClick={handleAddComment}
                disabled={!commentText.trim() || commentsLoading}
                style={{
                  padding: '10px 16px', borderRadius: '6px', background: '#4361EE', color: '#fff',
                  border: 'none', cursor: 'pointer', fontWeight: 700, fontSize: '0.85rem',
                  fontFamily: 'var(--font-heading)', opacity: !commentText.trim() ? 0.5 : 1,
                }}
              >
                ↵
              </button>
            </div>
          </div>
        )}

        {mode === 'edit' && (
          <div style={{ marginTop: '14px' }}>
            <label style={labelStyle}>Фотографии объекта</label>

            {/* Thumbnail grid */}
            {photos.length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px', marginBottom: '10px' }}>
                {photos.map((photo) => (
                  <div key={photo.name} style={{ position: 'relative', width: '80px', height: '80px' }}>
                    <img
                      src={photo.url}
                      alt={photo.name}
                      style={{ width: '80px', height: '80px', objectFit: 'cover', borderRadius: '8px', border: '1px solid var(--border-light)' }}
                    />
                    <button
                      onClick={() => deletePhoto(photo.name)}
                      style={{
                        position: 'absolute', top: '-6px', right: '-6px',
                        background: '#ef4444', color: '#fff', border: 'none',
                        borderRadius: '50%', width: '20px', height: '20px',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        cursor: 'pointer', padding: 0,
                      }}
                    >
                      <XIcon size={11} />
                    </button>
                  </div>
                ))}
              </div>
            )}

            {/* Upload button */}
            <label style={{
              display: 'inline-flex', alignItems: 'center', gap: '7px',
              padding: '8px 14px',
              border: '1.5px dashed var(--border-light)',
              borderRadius: '8px', cursor: uploading ? 'not-allowed' : 'pointer',
              fontSize: '0.85rem', color: 'var(--text-muted)',
              opacity: uploading ? 0.6 : 1,
            }}>
              <Camera size={15} />
              {uploading ? 'Загрузка...' : 'Добавить фото'}
              <input
                type="file"
                accept="image/*"
                multiple
                disabled={uploading}
                onChange={(e) => uploadPhotos(e.target.files)}
                style={{ display: 'none' }}
              />
            </label>
          </div>
        )}

        {error && <p role="alert" style={{ color: '#ef4444', fontSize: '0.85rem', marginTop: '10px' }}>{error}</p>}

        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '20px' }}>
          {mode === 'edit' && (
            <button
              onClick={handleDownloadPDF}
              disabled={downloading}
              style={{
                display: 'flex', alignItems: 'center', gap: '7px',
                background: 'none', border: '1.5px solid #E9ECEF',
                borderRadius: '8px', padding: '8px 16px',
                fontSize: '0.88rem', fontFamily: 'var(--font-heading)',
                fontWeight: 600, color: 'var(--text-main)',
                cursor: downloading ? 'not-allowed' : 'pointer',
                opacity: downloading ? 0.7 : 1,
                marginRight: 'auto',
              }}
            >
              <FileText size={15} />
              {downloading ? 'Генерация...' : 'Скачать PDF'}
            </button>
          )}
          <button
            onClick={handleSave}
            disabled={saving}
            className="btn-primary"
            style={{ display: 'flex', alignItems: 'center', gap: '8px', opacity: saving ? 0.7 : 1, cursor: saving ? 'not-allowed' : 'pointer' }}
          >
            <Save size={15} />
            {saving ? 'Сохранение...' : 'Сохранить'}
          </button>
        </div>

        {/* Event log */}
        {mode === 'edit' && events.length > 0 && (
          <div style={{ marginTop: '28px', borderTop: '1px solid var(--border-light)', paddingTop: '20px' }}>
            <h3 style={{ fontFamily: 'var(--font-heading)', fontSize: '0.9rem', fontWeight: 700, marginBottom: '12px' }}>
              История изменений
            </h3>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {events.map((e, i) => (
                <div key={e.id} style={{ display: 'flex', gap: '12px', alignItems: 'flex-start' }}>
                  {/* Timeline dot + line */}
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
                    <div style={{
                      width: '10px', height: '10px', borderRadius: '50%', marginTop: '4px',
                      background: e.event_type === 'status_change' ? '#4361EE' : '#E9ECEF',
                      border: '2px solid #fff', boxShadow: '0 0 0 1.5px #4361EE',
                      flexShrink: 0,
                    }} />
                    {i < events.length - 1 && (
                      <div style={{ width: '1px', flex: 1, background: '#E9ECEF', minHeight: '20px', marginTop: '2px' }} />
                    )}
                  </div>
                  <div style={{ flex: 1, paddingBottom: i < events.length - 1 ? '14px' : 0 }}>
                    <div style={{ fontSize: '0.82rem', color: 'var(--text-main)', lineHeight: 1.4 }}>{e.description}</div>
                    <div style={{ fontSize: '0.7rem', color: 'var(--text-muted)', marginTop: '2px', display: 'flex', gap: '8px' }}>
                      <span>{new Date(e.created_at).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}</span>
                      {e.created_by && <span>· {e.created_by}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OrderModal;
