'use client';

import { useCallback, useEffect, useState } from 'react';
import { Plus, Search, Package, Tag } from 'lucide-react';
import { api } from '@/lib/api';
import { ServiceDialog } from '@/components/catalog/service-dialog';
import { PackageDialog } from '@/components/catalog/package-dialog';

type Service = {
  id: string;
  name: string;
  category: string | { id: string; name: string };
  price: number;
  duration: number;
  isActive: boolean;
};

function getCategoryName(cat: string | { id: string; name: string } | undefined): string {
  if (!cat) return '—';
  if (typeof cat === 'string') return cat;
  return cat.name;
}

type ServicePackage = {
  id: string;
  name: string;
  services: (string | { id: string; name: string })[];
  totalPrice: number;
  discountPercent: number;
  validDays: number;
  isActive: boolean;
};

type ServicesResponse = {
  data: Service[];
  hasMore: boolean;
  nextCursor: string | null;
};

type PackagesResponse = {
  data: ServicePackage[];
  hasMore: boolean;
  nextCursor: string | null;
};

export default function CatalogPage(): React.JSX.Element {
  const [tab, setTab] = useState<'services' | 'packages'>('services');
  const [search, setSearch] = useState('');
  const [services, setServices] = useState<Service[]>([]);
  const [packages, setPackages] = useState<ServicePackage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showServiceDialog, setShowServiceDialog] = useState(false);
  const [editService, setEditService] = useState<Service | null>(null);
  const [showPackageDialog, setShowPackageDialog] = useState(false);
  const [editPackage, setEditPackage] = useState<ServicePackage | null>(null);

  const loadData = useCallback(() => {
    setLoading(true);
    void Promise.all([
      api.get<ServicesResponse>('/catalog/services')
        .then((res) => setServices(res.data ?? []))
        .catch(() => setServices([])),
      api.get<PackagesResponse>('/catalog/packages')
        .then((res) => setPackages(res.data ?? []))
        .catch(() => setPackages([])),
    ])
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Не удалось загрузить каталог');
      })
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadData();
  }, [loadData]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={loadData}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  const filteredServices = services.filter((s) =>
    s.name.toLowerCase().includes(search.toLowerCase()) ||
    getCategoryName(s.category).toLowerCase().includes(search.toLowerCase())
  );

  const handleAddClick = () => {
    if (tab === 'services') {
      setShowServiceDialog(true);
    } else {
      setShowPackageDialog(true);
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Каталог услуг</h1>
        <button
          onClick={handleAddClick}
          className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          {tab === 'services' ? 'Добавить услугу' : 'Создать пакет'}
        </button>
      </div>

      <div className="flex gap-2 mb-6">
        <button
          onClick={() => setTab('services')}
          className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors ${
            tab === 'services'
              ? 'bg-primary text-white'
              : 'bg-card text-gray-600 border border-border hover:bg-gray-50'
          }`}
        >
          <Tag className="h-4 w-4" />
          Услуги ({services.length})
        </button>
        <button
          onClick={() => setTab('packages')}
          className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-colors ${
            tab === 'packages'
              ? 'bg-primary text-white'
              : 'bg-card text-gray-600 border border-border hover:bg-gray-50'
          }`}
        >
          <Package className="h-4 w-4" />
          Пакеты ({packages.length})
        </button>
      </div>

      {tab === 'services' && (
        <div className="bg-card rounded-xl shadow-sm border border-border">
          <div className="p-4 border-b border-border">
            <div className="relative max-w-md">
              <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="w-full pl-10 pr-4 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
              />
            </div>
          </div>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-border">
                  <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Название</th>
                  <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Категория</th>
                  <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Цена</th>
                  <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Длительность</th>
                  <th className="text-left px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Статус</th>
                </tr>
              </thead>
              <tbody>
                {filteredServices.map((service) => (
                  <tr
                    key={service.id}
                    onClick={() => setEditService(service)}
                    className="border-b border-border last:border-0 hover:bg-gray-50 transition-colors cursor-pointer"
                  >
                    <td className="px-6 py-4 text-sm font-medium text-gray-900">{service.name}</td>
                    <td className="px-6 py-4 text-sm text-gray-600">{getCategoryName(service.category)}</td>
                    <td className="px-6 py-4 text-sm text-gray-900 font-medium">
                      {service.price === 0 ? 'Бесплатно' : `${service.price.toLocaleString('ru-RU')} \u20BD`}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-600">{service.duration} мин</td>
                    <td className="px-6 py-4">
                      <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${
                        service.isActive ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
                      }`}>
                        {service.isActive ? 'Активна' : 'Неактивна'}
                      </span>
                    </td>
                  </tr>
                ))}
                {filteredServices.length === 0 && (
                  <tr>
                    <td colSpan={5} className="px-6 py-8 text-center text-sm text-muted">
                      Нет услуг
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'packages' && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {packages.length === 0 && (
            <div className="col-span-full text-center py-12 text-muted text-sm">
              Нет пакетов
            </div>
          )}
          {packages.map((pkg) => (
            <div key={pkg.id} className="bg-card rounded-xl p-6 shadow-sm border border-border">
              <div className="flex items-start justify-between mb-3">
                <h3 className="text-lg font-semibold text-gray-900">{pkg.name}</h3>
                <span className={`inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${
                  pkg.isActive ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600'
                }`}>
                  {pkg.isActive ? 'Активен' : 'Неактивен'}
                </span>
              </div>

              <div className="space-y-2 mb-4">
                <p className="text-sm text-gray-600">
                  Услуги: {(pkg.services ?? []).map((s) => typeof s === 'string' ? s : s.name).join(', ')}
                </p>
                <p className="text-sm text-gray-600">
                  Срок действия: {pkg.validDays} дней
                </p>
              </div>

              <div className="flex items-end justify-between pt-4 border-t border-border">
                <div>
                  <p className="text-2xl font-bold text-gray-900">
                    {pkg.totalPrice.toLocaleString('ru-RU')} {'\u20BD'}
                  </p>
                  {pkg.discountPercent > 0 && (
                    <p className="text-xs text-success font-medium mt-0.5">
                      Скидка {pkg.discountPercent}%
                    </p>
                  )}
                </div>
                <button
                  onClick={() => setEditPackage(pkg)}
                  className="text-sm text-primary font-medium hover:underline"
                >
                  Редактировать
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <ServiceDialog
        open={showServiceDialog}
        onClose={() => setShowServiceDialog(false)}
        onSaved={loadData}
      />

      <ServiceDialog
        open={!!editService}
        onClose={() => setEditService(null)}
        onSaved={loadData}
        service={editService}
      />

      <PackageDialog
        open={showPackageDialog}
        onClose={() => setShowPackageDialog(false)}
        onSaved={loadData}
      />

      <PackageDialog
        open={!!editPackage}
        onClose={() => setEditPackage(null)}
        onSaved={loadData}
        pkg={editPackage}
      />
    </div>
  );
}
