'use client';

import { useEffect, useState, useCallback } from 'react';
import {
  Plus,
  Check,
  X,
  MoreHorizontal,
} from 'lucide-react';
import { cn } from '@/lib/cn';
import { api } from '@/lib/api';
import { IssueLicenseDialog } from '@/components/licenses/issue-license-dialog';

const licenseTypes = [
  {
    id: 'starter',
    name: 'Стартовая',
    price: '15 000 \u20BD/мес',
    color: 'border-gray-200 bg-white',
    badge: 'bg-gray-100 text-gray-700',
    features: {
      'Ядро CRM': true,
      'Продажи и реализация': true,
      'Координатор': true,
      'Push-уведомления': true,
      'Веб: Рецепция': true,
      'Веб: Отчёты': false,
      'SIP-телефония': false,
      'Запись звонков': false,
      'Webhooks + API': false,
      'Панель админа клуба': false,
      'Интеграция 1С': false,
    },
    limits: { users: 5, clients: 500 },
    activeCount: 0,
  },
  {
    id: 'standard',
    name: 'Стандартная',
    price: '35 000 \u20BD/мес',
    color: 'border-blue-200 bg-blue-50/30',
    badge: 'bg-blue-100 text-blue-700',
    features: {
      'Ядро CRM': true,
      'Продажи и реализация': true,
      'Координатор': true,
      'Push-уведомления': true,
      'Веб: Рецепция': true,
      'Веб: Отчёты': true,
      'SIP-телефония': true,
      'Запись звонков': false,
      'Webhooks + API': true,
      'Панель админа клуба': true,
      'Интеграция 1С': true,
    },
    limits: { users: 10, clients: 1000 },
    activeCount: 0,
  },
  {
    id: 'premium',
    name: 'Премиум',
    price: '75 000 \u20BD/мес',
    color: 'border-primary/30 bg-orange-50/30',
    badge: 'bg-primary/10 text-primary',
    features: {
      'Ядро CRM': true,
      'Продажи и реализация': true,
      'Координатор': true,
      'Push-уведомления': true,
      'Веб: Рецепция': true,
      'Веб: Отчёты': true,
      'SIP-телефония': true,
      'Запись звонков': true,
      'Webhooks + API': true,
      'Панель админа клуба': true,
      'Интеграция 1С': true,
    },
    limits: { users: 'Без лимита', clients: 'Без лимита' },
    activeCount: 0,
  },
];

interface ApiLicense {
  id: string;
  clubId: string;
  type: 'STARTER' | 'STANDARD' | 'PREMIUM';
  startDate: string;
  endDate: string;
  isActive: boolean;
  gracePeriodEnd: string | null;
  maxUsers: number;
  maxClients: number;
  createdAt: string;
  updatedAt: string;
  club: {
    id: string;
    name: string;
    slug: string;
  };
}

interface License {
  id: string;
  club: string;
  type: 'Стартовая' | 'Стандартная' | 'Премиум';
  status: 'active' | 'expiring' | 'expired' | 'trial';
  startDate: string;
  endDate: string;
  autoRenew: boolean;
}

const licenseTypeMap: Record<string, License['type']> = {
  STARTER: 'Стартовая',
  STANDARD: 'Стандартная',
  PREMIUM: 'Премиум',
};

const licenseTypeApiMap: Record<string, string> = {
  STARTER: 'starter',
  STANDARD: 'standard',
  PREMIUM: 'premium',
};

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  });
}

function mapApiLicense(apiLic: ApiLicense): License {
  const now = new Date();
  const endDate = new Date(apiLic.endDate);
  const startDate = new Date(apiLic.startDate);
  const daysUntilExpiry = Math.ceil(
    (endDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
  );
  const licenseDuration = Math.ceil(
    (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24),
  );

  let status: License['status'] = 'active';
  if (!apiLic.isActive || daysUntilExpiry < 0) {
    status = 'expired';
  } else if (licenseDuration <= 30) {
    status = 'trial';
  } else if (daysUntilExpiry <= 7) {
    status = 'expiring';
  } else {
    status = 'active';
  }

  return {
    id: apiLic.id.substring(0, 8).toUpperCase(),
    club: apiLic.club.name,
    type: licenseTypeMap[apiLic.type] || 'Стартовая',
    status,
    startDate: formatDate(apiLic.startDate),
    endDate: formatDate(apiLic.endDate),
    autoRenew: apiLic.isActive && daysUntilExpiry > 0,
  };
}

const statusLabels: Record<License['status'], string> = {
  active: 'Активна',
  expiring: 'Истекает',
  expired: 'Истекла',
  trial: 'Пробная',
};

const statusColors: Record<License['status'], string> = {
  active: 'bg-green-100 text-success',
  expiring: 'bg-orange-100 text-orange-700',
  expired: 'bg-red-100 text-error',
  trial: 'bg-blue-100 text-blue-700',
};

const typeColors: Record<License['type'], string> = {
  'Стартовая': 'bg-gray-100 text-gray-700',
  'Стандартная': 'bg-blue-100 text-blue-700',
  'Премиум': 'bg-primary/10 text-primary',
};

export default function LicensesPage() {
  const [tab, setTab] = useState<'types' | 'list'>('types');
  const [licenses, setLicenses] = useState<License[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [typeCounts, setTypeCounts] = useState<Record<string, number>>({
    starter: 0,
    standard: 0,
    premium: 0,
  });
  const [showIssueDialog, setShowIssueDialog] = useState(false);

  const loadLicenses = useCallback(() => {
    setLoading(true);
    setError(null);
    api
      .get<{ data: ApiLicense[]; hasMore: boolean; nextCursor: string | null }>(
        '/licenses?limit=100',
      )
      .then((res) => {
        const mapped = res.data.map(mapApiLicense);
        setLicenses(mapped);

        // Count active licenses per type
        const counts: Record<string, number> = {
          starter: 0,
          standard: 0,
          premium: 0,
        };
        for (const apiLic of res.data) {
          const key = licenseTypeApiMap[apiLic.type];
          if (key && apiLic.isActive) {
            counts[key] = (counts[key] || 0) + 1;
          }
        }
        setTypeCounts(counts);
      })
      .catch((err) => {
        const message =
          err instanceof Error ? err.message : 'Ошибка загрузки лицензий';
        setError(message);
      })
      .finally(() => setLoading(false));
  }, []);

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

  // Update licenseTypes with live counts
  const enrichedLicenseTypes = licenseTypes.map((type) => ({
    ...type,
    activeCount: typeCounts[type.id] || 0,
  }));

  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 flex-col items-center justify-center h-64 gap-4">
        <p className="text-sm text-error">{error}</p>
        <button
          onClick={() => window.location.reload()}
          className="text-sm text-primary hover:underline"
        >
          Попробовать снова
        </button>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">
            Управление лицензиями
          </h1>
          <p className="text-sm text-muted mt-1">
            {licenses.length} лицензий выдано
          </p>
        </div>
        <button
          onClick={() => setShowIssueDialog(true)}
          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" />
          Выдать лицензию
        </button>
      </div>

      <div className="flex gap-1 mb-6 bg-card rounded-lg p-1 border border-border w-fit">
        <button
          onClick={() => setTab('types')}
          className={cn(
            'px-4 py-2 rounded-md text-sm font-medium transition-colors',
            tab === 'types'
              ? 'bg-primary text-white'
              : 'text-muted hover:text-gray-900'
          )}
        >
          Типы лицензий
        </button>
        <button
          onClick={() => setTab('list')}
          className={cn(
            'px-4 py-2 rounded-md text-sm font-medium transition-colors',
            tab === 'list'
              ? 'bg-primary text-white'
              : 'text-muted hover:text-gray-900'
          )}
        >
          Список лицензий
        </button>
      </div>

      {tab === 'types' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {enrichedLicenseTypes.map((type) => (
            <div
              key={type.id}
              className={cn(
                'rounded-xl p-6 border-2 shadow-sm',
                type.color
              )}
            >
              <div className="flex items-center justify-between mb-4">
                <span
                  className={cn(
                    'px-3 py-1 rounded-full text-sm font-medium',
                    type.badge
                  )}
                >
                  {type.name}
                </span>
                <span className="text-sm text-muted">
                  {type.activeCount} активных
                </span>
              </div>

              <p className="text-2xl font-bold text-gray-900 mb-6">
                {type.price}
              </p>

              <div className="space-y-2.5 mb-6">
                {Object.entries(type.features).map(([feature, enabled]) => (
                  <div key={feature} className="flex items-center gap-2">
                    {enabled ? (
                      <Check className="h-4 w-4 text-success shrink-0" />
                    ) : (
                      <X className="h-4 w-4 text-gray-300 shrink-0" />
                    )}
                    <span
                      className={cn(
                        'text-sm',
                        enabled ? 'text-gray-700' : 'text-gray-400'
                      )}
                    >
                      {feature}
                    </span>
                  </div>
                ))}
              </div>

              <div className="pt-4 border-t border-border/50">
                <p className="text-xs text-muted mb-1">Лимиты:</p>
                <p className="text-sm text-gray-700">
                  Пользователи: {type.limits.users} | Клиенты:{' '}
                  {type.limits.clients}
                </p>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === 'list' && (
        <div className="bg-card rounded-xl shadow-sm 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">
                    ID
                  </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-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="px-4 py-3" />
                </tr>
              </thead>
              <tbody>
                {licenses.map((lic) => (
                  <tr
                    key={lic.id}
                    className="border-b border-border/50 hover:bg-background/30 transition-colors"
                  >
                    <td className="px-4 py-3 font-mono text-muted text-xs">
                      {lic.id}
                    </td>
                    <td className="px-4 py-3 font-medium text-gray-900">
                      {lic.club}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={cn(
                          'inline-block px-2.5 py-1 rounded-full text-xs font-medium',
                          typeColors[lic.type]
                        )}
                      >
                        {lic.type}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={cn(
                          'inline-block px-2.5 py-1 rounded-full text-xs font-medium',
                          statusColors[lic.status]
                        )}
                      >
                        {statusLabels[lic.status]}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-muted">{lic.startDate}</td>
                    <td className="px-4 py-3 text-muted">{lic.endDate}</td>
                    <td className="px-4 py-3 text-center">
                      {lic.autoRenew ? (
                        <Check className="h-4 w-4 text-success mx-auto" />
                      ) : (
                        <X className="h-4 w-4 text-gray-300 mx-auto" />
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <button className="p-1.5 rounded-lg hover:bg-background transition-colors">
                        <MoreHorizontal className="h-4 w-4 text-muted" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <IssueLicenseDialog
        open={showIssueDialog}
        onClose={() => setShowIssueDialog(false)}
        onCreated={loadLicenses}
      />
    </div>
  );
}
