'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { Plus, Settings, Search, Calendar, Loader2, Phone, Clock } from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';

type RecordStatus = 'PENDING' | 'CONFIRMED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED' | 'NO_SHOW';

interface BookingRecord {
  id: string;
  number: number;
  clientName: string;
  clientPhone: string;
  startAt: string;
  endAt: string;
  status: RecordStatus;
  source: string;
  places: number;
  price: string;
  service: { id: string; name: string; color: string | null } | null;
  staff: { id: string; firstName: string; lastName: string } | null;
  groupEvent: { id: string; title: string } | null;
}

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

const STATUS_LABELS: Record<RecordStatus, string> = {
  PENDING: 'Ожидает',
  CONFIRMED: 'Подтверждена',
  IN_PROGRESS: 'В процессе',
  COMPLETED: 'Завершена',
  CANCELLED: 'Отменена',
  NO_SHOW: 'Не пришёл',
};

const STATUS_COLORS: Record<RecordStatus, string> = {
  PENDING: 'bg-amber-100 text-amber-700',
  CONFIRMED: 'bg-blue-100 text-blue-700',
  IN_PROGRESS: 'bg-purple-100 text-purple-700',
  COMPLETED: 'bg-green-100 text-green-700',
  CANCELLED: 'bg-red-100 text-red-700',
  NO_SHOW: 'bg-gray-100 text-gray-700',
};

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 default function BookingsPage() {
  const [records, setRecords] = useState<BookingRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [staffFilter, setStaffFilter] = useState('');
  const [serviceFilter, setServiceFilter] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [cursor, setCursor] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(false);
  const [showCreate, setShowCreate] = useState(false);

  // Reference data
  const [services, setServices] = useState<Service[]>([]);
  const [staff, setStaff] = useState<StaffMember[]>([]);

  useEffect(() => {
    api
      .get<Service[]>('/booking/services')
      .then(setServices)
      .catch(() => {});
    api
      .get<StaffMember[]>('/users/staff')
      .then(setStaff)
      .catch(() => {});
  }, []);

  const fetchRecords = useCallback(
    async (append = false) => {
      setLoading(true);
      try {
        const params = new URLSearchParams();
        if (search) params.set('search', search);
        if (statusFilter) params.set('status', statusFilter);
        if (staffFilter) params.set('staffId', staffFilter);
        if (serviceFilter) params.set('serviceId', serviceFilter);
        if (dateFrom) params.set('from', dateFrom);
        if (dateTo) params.set('to', dateTo);
        if (append && cursor) params.set('cursor', cursor);
        params.set('limit', '50');

        const data = await api.get<{
          items: BookingRecord[];
          nextCursor: string | null;
          hasMore: boolean;
        }>(`/booking/records?${params}`);
        setRecords(append ? (prev) => [...prev, ...data.items] : data.items);
        setCursor(data.nextCursor);
        setHasMore(data.hasMore);
      } catch {
        // ignore
      } finally {
        setLoading(false);
      }
    },
    [search, statusFilter, staffFilter, serviceFilter, dateFrom, dateTo, cursor],
  );

  useEffect(() => {
    const t = setTimeout(() => fetchRecords(false), 300);
    return () => clearTimeout(t);
  }, [search, statusFilter, staffFilter, serviceFilter, dateFrom, dateTo]);

  const formatDate = (d: string) =>
    new Date(d).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
  const formatTime = (d: string) =>
    new Date(d).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' });

  return (
    <div>
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-xl font-bold text-text">Записи</h1>
          <p className="text-sm text-muted">Онлайн-запись клиентов на тренировки</p>
        </div>
        <div className="flex items-center gap-2">
          <Link
            href="/bookings/settings"
            className="flex items-center gap-2 px-3 py-2 rounded-lg border border-border text-sm text-muted hover:text-text hover:bg-background transition-colors"
          >
            <Settings className="h-4 w-4" />
            Настройки
          </Link>
          <button
            onClick={() => setShowCreate(true)}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            <Plus className="h-4 w-4" />
            Новая запись
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="relative flex-1 min-w-[200px] max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted" />
          <input
            type="text"
            placeholder="Поиск по имени или телефону..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className={cn(inputClass, 'pl-9')}
          />
        </div>
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className={cn(inputClass, 'w-auto')}
        >
          <option value="">Все статусы</option>
          {Object.entries(STATUS_LABELS).map(([k, v]) => (
            <option key={k} value={k}>
              {v}
            </option>
          ))}
        </select>
        <select
          value={serviceFilter}
          onChange={(e) => setServiceFilter(e.target.value)}
          className={cn(inputClass, 'w-auto')}
        >
          <option value="">Все услуги</option>
          {services.map((s) => (
            <option key={s.id} value={s.id}>
              {s.name}
            </option>
          ))}
        </select>
        <select
          value={staffFilter}
          onChange={(e) => setStaffFilter(e.target.value)}
          className={cn(inputClass, 'w-auto')}
        >
          <option value="">Все тренеры</option>
          {staff.map((s) => (
            <option key={s.id} value={s.id}>
              {s.firstName} {s.lastName}
            </option>
          ))}
        </select>
        <input
          type="date"
          value={dateFrom}
          onChange={(e) => setDateFrom(e.target.value)}
          className={cn(inputClass, 'w-auto')}
        />
        <span className="text-muted text-sm">—</span>
        <input
          type="date"
          value={dateTo}
          onChange={(e) => setDateTo(e.target.value)}
          className={cn(inputClass, 'w-auto')}
        />
      </div>

      {/* Table */}
      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <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 font-medium text-muted">#</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Клиент</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Услуга</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Тренер</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Дата / Время</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Статус</th>
                <th className="text-left px-4 py-3 font-medium text-muted">Источник</th>
                <th className="text-right px-4 py-3 font-medium text-muted">Сумма</th>
              </tr>
            </thead>
            <tbody>
              {records.map((r) => (
                <tr
                  key={r.id}
                  className="border-b border-border last:border-0 hover:bg-background/30 transition-colors cursor-pointer"
                >
                  <td className="px-4 py-3 text-muted">{r.number}</td>
                  <td className="px-4 py-3">
                    <div className="font-medium text-text">{r.clientName}</div>
                    <div className="text-xs text-muted flex items-center gap-1">
                      <Phone className="h-3 w-3" />
                      {r.clientPhone}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      {r.service?.color && (
                        <div
                          className="w-2 h-2 rounded-full shrink-0"
                          style={{ background: r.service.color }}
                        />
                      )}
                      <span className="text-text">{r.service?.name ?? '—'}</span>
                    </div>
                    {r.groupEvent && <div className="text-xs text-muted">{r.groupEvent.title}</div>}
                  </td>
                  <td className="px-4 py-3 text-text">
                    {r.staff ? `${r.staff.firstName} ${r.staff.lastName}` : '—'}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1 text-text">
                      <Calendar className="h-3.5 w-3.5 text-muted" />
                      {formatDate(r.startAt)}
                    </div>
                    <div className="flex items-center gap-1 text-xs text-muted">
                      <Clock className="h-3 w-3" />
                      {formatTime(r.startAt)} — {formatTime(r.endAt)}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={cn(
                        'px-2 py-1 rounded-full text-xs font-medium',
                        STATUS_COLORS[r.status],
                      )}
                    >
                      {STATUS_LABELS[r.status]}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-muted">{r.source}</td>
                  <td className="px-4 py-3 text-right font-medium text-text">
                    {Number(r.price).toLocaleString('ru-RU')} ₽
                  </td>
                </tr>
              ))}
              {records.length === 0 && !loading && (
                <tr>
                  <td colSpan={8} className="px-4 py-12 text-center text-muted">
                    Записей не найдено
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {loading && (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-5 w-5 animate-spin text-primary" />
          </div>
        )}

        {hasMore && !loading && (
          <div className="p-4 border-t border-border">
            <button
              onClick={() => fetchRecords(true)}
              className="w-full py-2 text-sm text-primary hover:text-primary/80 transition-colors"
            >
              Загрузить ещё
            </button>
          </div>
        )}
      </div>

      {/* Create Dialog */}
      {showCreate && (
        <CreateBookingDialog
          services={services}
          staff={staff}
          onClose={() => setShowCreate(false)}
          onCreated={() => {
            setShowCreate(false);
            fetchRecords(false);
          }}
        />
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// Create Booking Dialog
// ═══════════════════════════════════════════════════════════

function CreateBookingDialog({
  services,
  staff,
  onClose,
  onCreated,
}: {
  services: Service[];
  staff: StaffMember[];
  onClose: () => void;
  onCreated: () => void;
}) {
  const [clientName, setClientName] = useState('');
  const [clientPhone, setClientPhone] = useState('');
  const [clientEmail, setClientEmail] = useState('');
  const [serviceId, setServiceId] = useState('');
  const [staffId, setStaffId] = useState('');
  const [startDate, setStartDate] = useState('');
  const [startTime, setStartTime] = useState('');
  const [notes, setNotes] = useState('');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async () => {
    if (!clientName || !clientPhone || !serviceId || !staffId || !startDate || !startTime) {
      setError('Заполните все обязательные поля');
      return;
    }

    setSaving(true);
    setError('');

    try {
      await api.post('/booking/records', {
        clientName,
        clientPhone,
        clientEmail: clientEmail || undefined,
        serviceId,
        staffId,
        startAt: `${startDate}T${startTime}:00`,
        notes: notes || undefined,
        source: 'ADMIN',
      });
      onCreated();
    } catch (e: any) {
      setError(e.message || 'Ошибка создания записи');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
      onClick={onClose}
    >
      <div
        className="bg-card rounded-2xl border border-border shadow-xl w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-6 py-4 border-b border-border">
          <h2 className="text-lg font-semibold text-text">Новая запись</h2>
          <button onClick={onClose} className="text-muted hover:text-text text-xl">
            &times;
          </button>
        </div>

        <div className="px-6 py-4 space-y-4">
          {error && <div className="p-3 rounded-lg bg-red-50 text-red-700 text-sm">{error}</div>}

          <div>
            <label className="block text-sm font-medium text-text mb-1">Имя клиента *</label>
            <input
              value={clientName}
              onChange={(e) => setClientName(e.target.value)}
              className={inputClass}
              placeholder="Иван Петров"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Телефон *</label>
            <input
              value={clientPhone}
              onChange={(e) => setClientPhone(e.target.value)}
              className={inputClass}
              placeholder="+79001234567"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Email</label>
            <input
              value={clientEmail}
              onChange={(e) => setClientEmail(e.target.value)}
              className={inputClass}
              placeholder="ivan@mail.ru"
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-text mb-1">Услуга *</label>
              <select
                value={serviceId}
                onChange={(e) => setServiceId(e.target.value)}
                className={inputClass}
              >
                <option value="">Выбрать</option>
                {services.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-text mb-1">Тренер *</label>
              <select
                value={staffId}
                onChange={(e) => setStaffId(e.target.value)}
                className={inputClass}
              >
                <option value="">Выбрать</option>
                {staff.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.firstName} {s.lastName}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-text mb-1">Дата *</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text mb-1">Время *</label>
              <input
                type="time"
                value={startTime}
                onChange={(e) => setStartTime(e.target.value)}
                className={inputClass}
              />
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Примечание</label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              className={cn(inputClass, 'resize-none')}
              rows={2}
            />
          </div>
        </div>

        <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-border">
          <button
            onClick={onClose}
            className="px-4 py-2 rounded-lg border border-border text-sm text-muted hover:text-text transition-colors"
          >
            Отмена
          </button>
          <button
            onClick={handleSubmit}
            disabled={saving}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors"
          >
            {saving && <Loader2 className="h-4 w-4 animate-spin" />}
            Создать
          </button>
        </div>
      </div>
    </div>
  );
}
