'use client';

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

interface Pipeline {
  id: string;
  name: string;
  stages: { id: string; name: string; color: string }[];
}

interface CustomFieldDef {
  id: string;
  fieldName: string;
  name: string;
  type: string;
  isRequired: boolean;
  listOptions?: string[] | null;
  description?: string | null;
}

interface CreateDealDialogProps {
  open: boolean;
  onClose: () => void;
  onCreated: () => 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 CreateDealDialog({ open, onClose, onCreated }: CreateDealDialogProps) {
  const [title, setTitle] = useState('');
  const [contactName, setContactName] = useState('');
  const [contactPhone, setContactPhone] = useState('');
  const [contactEmail, setContactEmail] = useState('');
  const [source, setSource] = useState('MANUAL');
  const [pipelineId, setPipelineId] = useState('');
  const [amount, setAmount] = useState('');
  const [assigneeId, setAssigneeId] = useState('');
  const [staff, setStaff] = useState<{ id: string; firstName: string; lastName: string }[]>([]);
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  const [customFields, setCustomFields] = useState<CustomFieldDef[]>([]);
  const [customValues, setCustomValues] = useState<Record<string, any>>({});
  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) return;
    setTitle('');
    setContactName('');
    setContactPhone('');
    setContactEmail('');
    setSource('MANUAL');
    setAmount('');
    setAssigneeId('');
    setStaffSearch('');
    setCustomValues({});
    setError('');

    api
      .get<Pipeline[]>('/crm/pipelines')
      .then((data) => {
        setPipelines(data);
        if (data.length > 0 && !pipelineId) {
          const first = data[0];
          if (first) setPipelineId(first.id);
        }
      })
      .catch(() => {});

    api
      .get<CustomFieldDef[]>('/crm/fields?entityType=deal')
      .then(setCustomFields)
      .catch(() => {});
    api
      .get<{ id: string; firstName: string; lastName: string }[]>('/users/staff')
      .then((data) => {
        setStaff(data);
        // Default assignee = current user
        api
          .get<{ id: string; firstName: string; lastName: string }>('/auth/profile')
          .then((profile) => {
            setAssigneeId(profile.id);
            setStaffSearch(`${profile.firstName} ${profile.lastName}`);
          })
          .catch(() => {});
      })
      .catch(() => {});
  }, [open]);

  const selectedStaff = staff.find((s) => s.id === assigneeId);
  const filteredStaff = staff.filter((s) => {
    const name = `${s.firstName} ${s.lastName}`.toLowerCase();
    return name.includes(staffSearch.toLowerCase());
  });

  const handleSubmit = async () => {
    if (!title.trim()) {
      setError('Название обязательно');
      return;
    }
    setSaving(true);
    setError('');
    try {
      const body: Record<string, any> = {
        title: title.trim(),
        contactName: contactName.trim() || undefined,
        contactPhone: contactPhone.trim() || undefined,
        contactEmail: contactEmail.trim() || undefined,
        source,
        pipelineId: pipelineId || undefined,
        amount: amount ? parseFloat(amount) : undefined,
        assigneeId: assigneeId || undefined,
      };
      // Add custom field values
      const cfv: Record<string, any> = {};
      for (const [key, val] of Object.entries(customValues)) {
        if (val !== '' && val !== undefined && val !== null) cfv[key] = val;
      }
      if (Object.keys(cfv).length > 0) body.customFieldValues = cfv;

      await api.post('/crm/deals', body);
      onCreated();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка создания');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose}>
      <DialogHeader title="Новая сделка" onClose={onClose} />
      <DialogBody className="space-y-4">
        {error && (
          <div className="text-sm text-error bg-error/10 px-3 py-2 rounded-lg">{error}</div>
        )}

        <div>
          <label className="block text-sm font-medium text-text mb-1">Название *</label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Сделка с клиентом..."
            className={inputClass}
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Имя контакта</label>
            <input
              type="text"
              value={contactName}
              onChange={(e) => setContactName(e.target.value)}
              placeholder="Иван Иванов"
              className={inputClass}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Телефон</label>
            <input
              type="tel"
              value={contactPhone}
              onChange={(e) => setContactPhone(e.target.value)}
              placeholder="+7 (999) 123-45-67"
              className={inputClass}
            />
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-1">Email</label>
          <input
            type="email"
            value={contactEmail}
            onChange={(e) => setContactEmail(e.target.value)}
            placeholder="client@example.com"
            className={inputClass}
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Сумма</label>
            <input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              placeholder="0"
              min={0}
              className={inputClass}
            />
          </div>
          <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) setAssigneeId('');
              }}
              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={() => {
                      setAssigneeId(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 === assigneeId ? 'bg-primary/10 text-primary' : 'text-text'}`}
                  >
                    {s.firstName} {s.lastName}
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Воронка</label>
            <select
              value={pipelineId}
              onChange={(e) => setPipelineId(e.target.value)}
              className={inputClass}
            >
              {pipelines.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Источник</label>
            <select
              value={source}
              onChange={(e) => setSource(e.target.value)}
              className={inputClass}
            >
              <option value="MANUAL">Вручную</option>
              <option value="PHONE">Телефон</option>
              <option value="REFERRAL">Реферал</option>
              <option value="SOCIAL">Соцсети</option>
            </select>
          </div>
        </div>

        {/* Custom fields */}
        {customFields.length > 0 && (
          <div className="space-y-3 pt-2 border-t border-border/50">
            <span className="text-xs font-medium text-muted">Дополнительные поля</span>
            {customFields.map((field) => (
              <div key={field.id}>
                <label className="block text-sm font-medium text-text mb-1">
                  {field.name}
                  {field.isRequired ? ' *' : ''}
                </label>
                {field.type === 'LIST' ? (
                  <select
                    value={customValues[field.fieldName] || ''}
                    onChange={(e) =>
                      setCustomValues((v) => ({ ...v, [field.fieldName]: e.target.value }))
                    }
                    className={inputClass}
                  >
                    <option value="">—</option>
                    {(field.listOptions || []).map((opt) => (
                      <option key={opt} value={opt}>
                        {opt}
                      </option>
                    ))}
                  </select>
                ) : field.type === 'BOOLEAN' ? (
                  <label className="flex items-center gap-2 text-sm">
                    <input
                      type="checkbox"
                      checked={!!customValues[field.fieldName]}
                      onChange={(e) =>
                        setCustomValues((v) => ({ ...v, [field.fieldName]: e.target.checked }))
                      }
                      className="rounded border-border"
                    />
                    <span className="text-text">{field.description || 'Да'}</span>
                  </label>
                ) : field.type === 'DATE' || field.type === 'DATETIME' ? (
                  <input
                    type={field.type === 'DATE' ? 'date' : 'datetime-local'}
                    value={customValues[field.fieldName] || ''}
                    onChange={(e) =>
                      setCustomValues((v) => ({ ...v, [field.fieldName]: e.target.value }))
                    }
                    className={inputClass}
                  />
                ) : (
                  <input
                    type={field.type === 'INTEGER' || field.type === 'FLOAT' ? 'number' : 'text'}
                    value={customValues[field.fieldName] || ''}
                    onChange={(e) =>
                      setCustomValues((v) => ({ ...v, [field.fieldName]: e.target.value }))
                    }
                    placeholder={field.description || ''}
                    className={inputClass}
                  />
                )}
              </div>
            ))}
          </div>
        )}
      </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>
  );
}
