'use client';

import { useEffect, useState, useCallback } from 'react';
import { Plus, Trash2, Pencil, Loader2, X } from 'lucide-react';
import { useCrmApi } from '../context';
import type { CustomFieldDef } from '../types';

interface FieldManagerProps {
  entityType?: string;
}

const FIELD_TYPES = [
  { value: 'STRING', label: 'Строка' },
  { value: 'INTEGER', label: 'Целое число' },
  { value: 'FLOAT', label: 'Дробное число' },
  { value: 'LIST', label: 'Список' },
  { value: 'BOOLEAN', label: 'Да/Нет' },
  { value: 'DATE', label: 'Дата' },
  { value: 'DATETIME', label: 'Дата и время' },
];

const fieldTypeLabels: Record<string, string> = Object.fromEntries(
  FIELD_TYPES.map((t) => [t.value, t.label]),
);

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 bg-background text-text';

// Inline dialog (self-contained, no external Dialog dependency)
function InlineDialog({
  open,
  onClose,
  title,
  children,
  footer,
}: {
  open: boolean;
  onClose: () => void;
  title: string;
  children: React.ReactNode;
  footer: React.ReactNode;
}) {
  useEffect(() => {
    if (!open) return;
    const h = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', h);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose();
      }}
    >
      <div className="fixed inset-0 bg-black/50" />
      <div className="relative z-10 bg-card rounded-2xl shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
        <div className="flex items-start justify-between p-6 pb-0">
          <h2 className="text-lg font-semibold text-text">{title}</h2>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg hover:bg-muted/20 transition-colors -mt-1 -mr-1"
          >
            <X className="h-4 w-4 text-muted" />
          </button>
        </div>
        <div className="p-6 space-y-4">{children}</div>
        <div className="flex items-center justify-end gap-3 px-6 pb-6">{footer}</div>
      </div>
    </div>
  );
}

export function FieldManager({ entityType = 'deal' }: FieldManagerProps) {
  const api = useCrmApi();
  const [fields, setFields] = useState<CustomFieldDef[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<CustomFieldDef | null>(null);
  const [name, setName] = useState('');
  const [fieldName, setFieldName] = useState('');
  const [type, setType] = useState('STRING');
  const [isRequired, setIsRequired] = useState(false);
  const [showToTrainer, setShowToTrainer] = useState(false);
  const [description, setDescription] = useState('');
  const [listOptions, setListOptions] = useState('');
  const [saving, setSaving] = useState(false);

  const fetchFields = useCallback(async () => {
    try {
      const data = await api.get<CustomFieldDef[]>(`/crm/fields?entityType=${entityType}`);
      setFields(data);
    } catch {
      /**/
    } finally {
      setLoading(false);
    }
  }, [api, entityType]);

  useEffect(() => {
    setLoading(true);
    void fetchFields();
  }, [fetchFields]);

  const openCreate = () => {
    setEditing(null);
    setName('');
    setFieldName('');
    setType('STRING');
    setIsRequired(false);
    setShowToTrainer(false);
    setDescription('');
    setListOptions('');
    setShowForm(true);
  };

  const openEdit = (field: CustomFieldDef) => {
    setEditing(field);
    setName(field.name);
    setFieldName(field.fieldName);
    setType(field.type);
    setIsRequired(field.isRequired);
    setShowToTrainer(field.showToTrainer);
    setDescription(field.description || '');
    setListOptions(Array.isArray(field.listOptions) ? field.listOptions.join('\n') : '');
    setShowForm(true);
  };

  const handleSave = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const data: Record<string, unknown> = {
        name: name.trim(),
        type,
        isRequired,
        showToTrainer,
        description: description.trim() || undefined,
      };
      if (type === 'LIST' && listOptions.trim())
        data.listOptions = listOptions
          .split('\n')
          .map((s) => s.trim())
          .filter(Boolean);
      if (editing) {
        await api.patch(`/crm/fields/${editing.id}`, data);
      } else {
        data.entityType = entityType;
        data.fieldName = fieldName.trim();
        await api.post('/crm/fields', data);
      }
      setShowForm(false);
      await fetchFields();
    } catch (err: unknown) {
      alert(err instanceof Error ? err.message : 'Ошибка сохранения');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Деактивировать поле? Данные сохранятся, но поле будет скрыто.')) return;
    try {
      await api.delete(`/crm/fields/${id}`);
      await fetchFields();
    } catch {
      /**/
    }
  };

  const handleNameChange = (val: string) => {
    setName(val);
    if (!editing) {
      const transliterated = val
        .toLowerCase()
        .replace(/[а-яё]/g, (c) => {
          const map: Record<string, string> = {
            а: 'a',
            б: 'b',
            в: 'v',
            г: 'g',
            д: 'd',
            е: 'e',
            ё: 'e',
            ж: 'zh',
            з: 'z',
            и: 'i',
            й: 'y',
            к: 'k',
            л: 'l',
            м: 'm',
            н: 'n',
            о: 'o',
            п: 'p',
            р: 'r',
            с: 's',
            т: 't',
            у: 'u',
            ф: 'f',
            х: 'kh',
            ц: 'ts',
            ч: 'ch',
            ш: 'sh',
            щ: 'sch',
            ъ: '',
            ы: 'y',
            ь: '',
            э: 'e',
            ю: 'yu',
            я: 'ya',
          };
          return map[c] || c;
        })
        .replace(/[^a-z0-9]+/g, '_')
        .replace(/^_|_$/g, '');
      setFieldName(transliterated);
    }
  };

  if (loading)
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    );

  return (
    <div>
      <div className="flex justify-end mb-4">
        <button
          onClick={openCreate}
          className="flex items-center gap-1.5 px-4 py-2 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Добавить поле
        </button>
      </div>

      <div className="bg-card rounded-xl border border-border">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-background/50">
                <th className="text-left px-4 py-3 text-muted font-medium">Название</th>
                <th className="text-left px-4 py-3 text-muted font-medium">Код</th>
                <th className="text-left px-4 py-3 text-muted font-medium">Тип</th>
                <th className="text-center px-4 py-3 text-muted font-medium">Обязательное</th>
                <th className="text-center px-4 py-3 text-muted font-medium">Тренер</th>
                <th className="text-right px-4 py-3 text-muted font-medium w-24">Действия</th>
              </tr>
            </thead>
            <tbody>
              {fields.map((field) => (
                <tr key={field.id} className="border-b border-border/50 group">
                  <td className="px-4 py-3">
                    <div className="font-medium text-text">{field.name}</div>
                    {field.description && (
                      <div className="text-xs text-muted">{field.description}</div>
                    )}
                  </td>
                  <td className="px-4 py-3 text-muted font-mono text-xs">{field.fieldName}</td>
                  <td className="px-4 py-3 text-muted">
                    {fieldTypeLabels[field.type] || field.type}
                  </td>
                  <td className="px-4 py-3 text-center">{field.isRequired ? 'Да' : '—'}</td>
                  <td className="px-4 py-3 text-center">{field.showToTrainer ? 'Да' : '—'}</td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex items-center justify-end gap-1">
                      <button
                        onClick={() => openEdit(field)}
                        className="p-1.5 rounded-lg hover:bg-background text-muted hover:text-text transition-colors"
                      >
                        <Pencil className="h-3.5 w-3.5" />
                      </button>
                      <button
                        onClick={() => void handleDelete(field.id)}
                        className="p-1.5 rounded-lg hover:bg-error/10 text-muted hover:text-error transition-colors"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {fields.length === 0 && (
                <tr>
                  <td colSpan={6} className="text-center py-8 text-muted">
                    Нет кастомных полей
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <InlineDialog
        open={showForm}
        onClose={() => setShowForm(false)}
        title={editing ? 'Редактировать поле' : 'Новое поле'}
        footer={
          <>
            <button
              onClick={() => setShowForm(false)}
              className="px-4 py-2 text-sm text-muted hover:text-text transition-colors"
            >
              Отмена
            </button>
            <button
              onClick={() => void handleSave()}
              disabled={saving || !name.trim() || (!editing && !fieldName.trim())}
              className="px-4 py-2 text-sm bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50 transition-colors"
            >
              {saving ? 'Сохранение...' : 'Сохранить'}
            </button>
          </>
        }
      >
        <div>
          <label className="block text-sm font-medium text-text mb-1">Название</label>
          <input
            type="text"
            value={name}
            onChange={(e) => handleNameChange(e.target.value)}
            placeholder="Размер ноги"
            className={inputClass}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Код (snake_case)</label>
          <input
            type="text"
            value={fieldName}
            onChange={(e) => setFieldName(e.target.value)}
            placeholder="shoe_size"
            disabled={!!editing}
            className={`${inputClass} ${editing ? 'opacity-50' : ''}`}
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-text mb-1">Тип</label>
          <select value={type} onChange={(e) => setType(e.target.value)} className={inputClass}>
            {FIELD_TYPES.map((t) => (
              <option key={t.value} value={t.value}>
                {t.label}
              </option>
            ))}
          </select>
        </div>
        {type === 'LIST' && (
          <div>
            <label className="block text-sm font-medium text-text mb-1">
              Опции (по одной на строке)
            </label>
            <textarea
              value={listOptions}
              onChange={(e) => setListOptions(e.target.value)}
              rows={4}
              placeholder="Опция 1&#10;Опция 2&#10;Опция 3"
              className={inputClass}
            />
          </div>
        )}
        <div>
          <label className="block text-sm font-medium text-text mb-1">Описание</label>
          <input
            type="text"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Подсказка для менеджера"
            className={inputClass}
          />
        </div>
        <div className="flex items-center gap-4">
          <label className="flex items-center gap-2 text-sm text-text cursor-pointer">
            <input
              type="checkbox"
              checked={isRequired}
              onChange={(e) => setIsRequired(e.target.checked)}
              className="rounded border-border"
            />
            Обязательное
          </label>
          <label className="flex items-center gap-2 text-sm text-text cursor-pointer">
            <input
              type="checkbox"
              checked={showToTrainer}
              onChange={(e) => setShowToTrainer(e.target.checked)}
              className="rounded border-border"
            />
            Показывать тренеру
          </label>
        </div>
      </InlineDialog>
    </div>
  );
}
