'use client';

import { useState, useEffect, useRef } from 'react';
import { api } from '@/lib/api';
import { Dialog, DialogHeader, DialogBody, DialogFooter } from '@/components/ui/dialog';

interface DealData {
  id: string;
  title: string;
  contactName?: string;
  contactPhone?: string;
  contactEmail?: string;
  contactTelegram?: string;
  contactWhatsapp?: string;
  contactVk?: string;
  companyName?: string;
  companyInn?: string;
  companyKpp?: string;
  companyOgrn?: string;
  companyLegalAddress?: string;
  companyBankAccount?: string;
  companyBik?: string;
  companyBankName?: string;
  source?: string;
  amount?: number;
  assigneeId?: string;
  probability?: number;
  expectedCloseDate?: string;
}

interface StaffMember {
  id: string;
  firstName: string;
  lastName: string;
}

interface EditDealDialogProps {
  open: boolean;
  deal: DealData | null;
  onClose: () => void;
  onSaved: () => void;
}

const inputClass =
  'w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary bg-background text-text';

export function EditDealDialog({ open, deal, onClose, onSaved }: EditDealDialogProps) {
  const [form, setForm] = useState<Record<string, any>>({});
  const [staff, setStaff] = useState<StaffMember[]>([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [staffSearch, setStaffSearch] = useState('');
  const [showStaffDropdown, setShowStaffDropdown] = useState(false);
  const staffRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (staffRef.current && !staffRef.current.contains(e.target as Node)) {
        setShowStaffDropdown(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  useEffect(() => {
    if (!open || !deal) return;
    setStaffSearch('');
    setForm({
      title: deal.title || '',
      contactName: deal.contactName || '',
      contactPhone: deal.contactPhone || '',
      contactEmail: deal.contactEmail || '',
      contactTelegram: deal.contactTelegram || '',
      contactWhatsapp: deal.contactWhatsapp || '',
      contactVk: deal.contactVk || '',
      companyName: deal.companyName || '',
      companyInn: deal.companyInn || '',
      companyKpp: deal.companyKpp || '',
      companyOgrn: deal.companyOgrn || '',
      companyLegalAddress: deal.companyLegalAddress || '',
      companyBankAccount: deal.companyBankAccount || '',
      companyBik: deal.companyBik || '',
      companyBankName: deal.companyBankName || '',
      source: deal.source || 'MANUAL',
      amount: deal.amount?.toString() || '',
      assigneeId: deal.assigneeId || '',
      probability: deal.probability?.toString() || '',
      expectedCloseDate: deal.expectedCloseDate?.split('T')[0] || '',
    });
    setError('');

    // Load staff for assignee picker
    api
      .get<StaffMember[]>('/users/staff')
      .then(setStaff)
      .catch(() => {});
  }, [open, deal]);

  const set = (key: string, value: string) => setForm((f) => ({ ...f, [key]: value }));
  const selectedStaff = staff.find((s) => s.id === form.assigneeId);
  const filteredStaff = staff.filter((s) => {
    const name = `${s.firstName} ${s.lastName}`.toLowerCase();
    return name.includes(staffSearch.toLowerCase());
  });

  const handleSubmit = async () => {
    if (!deal || !form.title?.trim()) {
      setError('Название обязательно');
      return;
    }
    setSaving(true);
    setError('');
    try {
      const data: Record<string, any> = {};
      for (const [key, value] of Object.entries(form)) {
        if (key === 'amount') {
          data[key] = value ? parseFloat(value) : null;
        } else if (key === 'probability') {
          data[key] = value ? parseInt(value) : null;
        } else if (key === 'expectedCloseDate') {
          data[key] = value || null;
        } else if (key === 'assigneeId') {
          data[key] = value || null;
        } else {
          data[key] = (value as string).trim() || undefined;
        }
      }
      await api.patch(`/crm/deals/${deal.id}`, data);
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка сохранения');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} className="max-w-2xl">
      <DialogHeader title="Редактировать сделку" onClose={onClose} />
      <DialogBody className="space-y-4 max-h-[60vh] overflow-y-auto">
        {error && (
          <div className="text-sm text-error bg-error/10 px-3 py-2 rounded-lg">{error}</div>
        )}

        {/* Title */}
        <div>
          <label className="block text-sm font-medium text-text mb-1">Название *</label>
          <input
            type="text"
            value={form.title || ''}
            onChange={(e) => set('title', e.target.value)}
            className={inputClass}
          />
        </div>

        {/* Contact */}
        <fieldset className="border border-border/50 rounded-lg p-3 space-y-3">
          <legend className="text-xs font-medium text-muted px-1">Контакт</legend>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Имя" value={form.contactName} onChange={(v) => set('contactName', v)} />
            <Field
              label="Телефон"
              value={form.contactPhone}
              onChange={(v) => set('contactPhone', v)}
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field
              label="Email"
              value={form.contactEmail}
              onChange={(v) => set('contactEmail', v)}
              type="email"
            />
            <Field
              label="Telegram"
              value={form.contactTelegram}
              onChange={(v) => set('contactTelegram', v)}
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <Field
              label="WhatsApp"
              value={form.contactWhatsapp}
              onChange={(v) => set('contactWhatsapp', v)}
            />
            <Field label="VK" value={form.contactVk} onChange={(v) => set('contactVk', v)} />
          </div>
        </fieldset>

        {/* Deal info */}
        <div className="grid grid-cols-3 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Сумма</label>
            <input
              type="number"
              value={form.amount || ''}
              onChange={(e) => set('amount', e.target.value)}
              min={0}
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Источник</label>
            <select
              value={form.source || ''}
              onChange={(e) => set('source', e.target.value)}
              className={inputClass}
            >
              <option value="MANUAL">Вручную</option>
              <option value="LANDING">Лендинг</option>
              <option value="WEBHOOK">Вебхук</option>
              <option value="PHONE">Телефон</option>
              <option value="REFERRAL">Реферал</option>
              <option value="SOCIAL">Соцсети</option>
              <option value="IMPORT">Импорт</option>
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Вероятность %</label>
            <input
              type="number"
              value={form.probability || ''}
              onChange={(e) => set('probability', e.target.value)}
              min={0}
              max={100}
              className={inputClass}
            />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div className="relative" ref={staffRef}>
            <label className="block text-sm font-medium text-text mb-1">Ответственный</label>
            <input
              type="text"
              value={
                showStaffDropdown
                  ? staffSearch
                  : selectedStaff
                    ? `${selectedStaff.firstName} ${selectedStaff.lastName}`
                    : staffSearch
              }
              onChange={(e) => {
                setStaffSearch(e.target.value);
                setShowStaffDropdown(true);
                if (!e.target.value) set('assigneeId', '');
              }}
              onFocus={() => {
                setShowStaffDropdown(true);
                setStaffSearch('');
              }}
              placeholder="Поиск сотрудника..."
              className={inputClass}
            />
            {showStaffDropdown && filteredStaff.length > 0 && (
              <div className="absolute z-10 top-full left-0 right-0 mt-1 bg-card border border-border rounded-lg shadow-lg max-h-40 overflow-y-auto">
                {filteredStaff.map((s) => (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() => {
                      set('assigneeId', s.id);
                      setStaffSearch(`${s.firstName} ${s.lastName}`);
                      setShowStaffDropdown(false);
                    }}
                    className={`w-full text-left px-3 py-2 text-sm hover:bg-background transition-colors ${s.id === form.assigneeId ? 'bg-primary/10 text-primary' : 'text-text'}`}
                  >
                    {s.firstName} {s.lastName}
                  </button>
                ))}
              </div>
            )}
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Ожидаемое закрытие</label>
            <input
              type="date"
              value={form.expectedCloseDate || ''}
              onChange={(e) => set('expectedCloseDate', e.target.value)}
              className={inputClass}
            />
          </div>
        </div>

        {/* Company (B2B) */}
        <fieldset className="border border-border/50 rounded-lg p-3 space-y-3">
          <legend className="text-xs font-medium text-muted px-1">Компания (B2B)</legend>
          <div className="grid grid-cols-2 gap-3">
            <Field
              label="Название"
              value={form.companyName}
              onChange={(v) => set('companyName', v)}
            />
            <Field label="ИНН" value={form.companyInn} onChange={(v) => set('companyInn', v)} />
          </div>
          <div className="grid grid-cols-3 gap-3">
            <Field label="КПП" value={form.companyKpp} onChange={(v) => set('companyKpp', v)} />
            <Field label="ОГРН" value={form.companyOgrn} onChange={(v) => set('companyOgrn', v)} />
            <Field label="БИК" value={form.companyBik} onChange={(v) => set('companyBik', v)} />
          </div>
          <Field
            label="Юр. адрес"
            value={form.companyLegalAddress}
            onChange={(v) => set('companyLegalAddress', v)}
          />
          <div className="grid grid-cols-2 gap-3">
            <Field
              label="Р/С"
              value={form.companyBankAccount}
              onChange={(v) => set('companyBankAccount', v)}
            />
            <Field
              label="Банк"
              value={form.companyBankName}
              onChange={(v) => set('companyBankName', v)}
            />
          </div>
        </fieldset>
      </DialogBody>
      <DialogFooter>
        <button
          onClick={onClose}
          className="px-4 py-2 text-sm text-muted hover:text-text transition-colors"
        >
          Отмена
        </button>
        <button
          onClick={handleSubmit}
          disabled={saving}
          className="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50"
        >
          {saving ? 'Сохранение...' : 'Сохранить'}
        </button>
      </DialogFooter>
    </Dialog>
  );
}

function Field({
  label,
  value,
  onChange,
  type = 'text',
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
}) {
  return (
    <div>
      <label className="block text-sm font-medium text-text mb-1">{label}</label>
      <input
        type={type}
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 bg-background text-text"
      />
    </div>
  );
}
