import React, { useState, useEffect } from 'react';
import { X, Save, FileText, Camera, X as XIcon } from 'lucide-react';
import { useOrderPhotos } from './useOrderPhotos';
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 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 || '',
  });
  const [events, setEvents] = useState([]);
  const { photos, uploading, uploadPhotos, deletePhoto } = useOrderPhotos(mode === 'edit' ? order?.id : null);
  const [saving, setSaving] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [error, setError] = 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 : f.scheduled_at,
  });

  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>
          <button
            onClick={onClose}
            aria-label="Закрыть"
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-muted)' }}
          >
            <X size={20} />
          </button>
        </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 ? new Date(form.scheduled_at).toISOString().slice(0, 16) : ''}
              onChange={(e) => setForm((prev) => ({ ...prev, scheduled_at: e.target.value ? new Date(e.target.value).toISOString() : '' }))}
              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' }}>
            <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', gap: '8px' }}>
              {events.map((e) => (
                <div key={e.id} style={{ fontSize: '0.8rem', color: 'var(--text-muted)', display: 'flex', gap: '10px', alignItems: 'baseline' }}>
                  <span style={{ color: 'var(--accent-blue)', fontWeight: 600, flexShrink: 0 }}>
                    {new Date(e.created_at).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                  </span>
                  <span style={{ flex: 1 }}>{e.description}</span>
                  {e.created_by && (
                    <span style={{ opacity: 0.55, flexShrink: 0, fontSize: '0.72rem' }}>{e.created_by}</span>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default OrderModal;
