'use client';

import { useCallback, useEffect, useState } from 'react';
import {
  KeyRound,
  Calendar,
  CheckCircle,
  AlertTriangle,
  Package,
  BarChart3,
} from 'lucide-react';
import { api } from '@/lib/api';
import { RenewDialog } from '@/components/license/renew-dialog';

type Module = {
  id: string;
  name: string;
  enabled: boolean;
  description: string;
};

type ModulesResponse = {
  data: Module[];
};

type UsageItem = {
  label: string;
  current: number;
  limit: number;
  unit: string;
};

type LicenseInfo = {
  type: string;
  clubName: string;
  activatedAt: string;
  expiresAt: string;
  daysLeft: number;
  status: 'active' | 'expired' | 'grace';
};

type UsageData = {
  active_users?: { current: number; limit: number };
  clients?: { current: number; limit: number };
  call_storage_gb?: { current: number; limit: number };
  webhooks_sent?: { current: number; limit: number };
  api_requests?: { current: number; limit: number };
  push_sent?: { current: number; limit: number };
};

const defaultLicenseInfo: LicenseInfo = {
  type: '\u2014',
  clubName: '\u2014',
  activatedAt: '\u2014',
  expiresAt: '\u2014',
  daysLeft: 0,
  status: 'active',
};

function mapUsageData(data: UsageData): UsageItem[] {
  return [
    { label: 'Активные пользователи', current: data.active_users?.current ?? 0, limit: data.active_users?.limit ?? 0, unit: 'чел.' },
    { label: 'Клиентская база', current: data.clients?.current ?? 0, limit: data.clients?.limit ?? 0, unit: 'записей' },
    { label: 'Записи звонков', current: data.call_storage_gb?.current ?? 0, limit: data.call_storage_gb?.limit ?? 0, unit: 'ГБ' },
    { label: 'Webhook-доставка', current: data.webhooks_sent?.current ?? 0, limit: data.webhooks_sent?.limit ?? 0, unit: 'событий/мес' },
    { label: 'API-запросы', current: data.api_requests?.current ?? 0, limit: data.api_requests?.limit ?? 0, unit: 'запросов/мес' },
    { label: 'Push-уведомления', current: data.push_sent?.current ?? 0, limit: data.push_sent?.limit ?? 0, unit: 'сообщ./мес' },
  ];
}

const defaultUsage: UsageItem[] = [
  { label: 'Активные пользователи', current: 0, limit: 0, unit: 'чел.' },
  { label: 'Клиентская база', current: 0, limit: 0, unit: 'записей' },
  { label: 'Записи звонков', current: 0, limit: 0, unit: 'ГБ' },
  { label: 'Webhook-доставка', current: 0, limit: 0, unit: 'событий/мес' },
  { label: 'API-запросы', current: 0, limit: 0, unit: 'запросов/мес' },
  { label: 'Push-уведомления', current: 0, limit: 0, unit: 'сообщ./мес' },
];

export default function LicensePage(): React.JSX.Element {
  const [licenseInfo, setLicenseInfo] = useState<LicenseInfo>(defaultLicenseInfo);
  const [modules, setModules] = useState<Module[]>([]);
  const [usage, setUsage] = useState<UsageItem[]>(defaultUsage);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showRenewDialog, setShowRenewDialog] = useState(false);

  const loadData = useCallback(() => {
    setLoading(true);
    setError(null);
    void Promise.all([
      api.get<LicenseInfo>('/licenses/my')
        .then((res) => setLicenseInfo(res))
        .catch(() => {}),
      api.get<UsageData>('/metering/usage')
        .then((res) => setUsage(mapUsageData(res)))
        .catch(() => {}),
      api.get<ModulesResponse>('/modules')
        .then((res) => setModules(res.data ?? []))
        .catch(() => setModules([])),
    ])
      .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 statusBadge = licenseInfo.status === 'active'
    ? { label: 'Активна', className: 'bg-green-100 text-green-800' }
    : licenseInfo.status === 'grace'
      ? { label: 'Льготный период', className: 'bg-yellow-100 text-yellow-800' }
      : { label: 'Истекла', className: 'bg-red-100 text-red-800' };

  const daysColor = licenseInfo.daysLeft > 30 ? 'text-success' : licenseInfo.daysLeft > 7 ? 'text-yellow-600' : 'text-error';

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">Лицензия</h1>

      <div className="bg-card rounded-xl p-6 shadow-sm border border-border mb-8">
        <div className="flex items-start gap-4 mb-6">
          <div className="bg-orange-50 text-primary p-3 rounded-lg">
            <KeyRound className="h-6 w-6" />
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-3 mb-1">
              <h2 className="text-lg font-semibold text-gray-900">
                Лицензия: {licenseInfo.type}
              </h2>
              <span className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium ${statusBadge.className}`}>
                <CheckCircle className="h-3 w-3" />
                {statusBadge.label}
              </span>
            </div>
            <p className="text-sm text-gray-600">{licenseInfo.clubName}</p>
          </div>
          <button
            onClick={() => setShowRenewDialog(true)}
            className="px-4 py-2 rounded-xl bg-primary text-white text-sm font-medium hover:bg-primary/90 transition-colors"
          >
            Продлить
          </button>
        </div>

        <div className="grid grid-cols-3 gap-6">
          <div className="flex items-center gap-3">
            <Calendar className="h-5 w-5 text-muted" />
            <div>
              <p className="text-xs text-muted">Активирована</p>
              <p className="text-sm font-medium text-gray-900">{licenseInfo.activatedAt}</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <Calendar className="h-5 w-5 text-muted" />
            <div>
              <p className="text-xs text-muted">Истекает</p>
              <p className="text-sm font-medium text-gray-900">{licenseInfo.expiresAt}</p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <AlertTriangle className={`h-5 w-5 ${daysColor}`} />
            <div>
              <p className="text-xs text-muted">Осталось дней</p>
              <p className={`text-sm font-medium ${daysColor}`}>{licenseInfo.daysLeft}</p>
            </div>
          </div>
        </div>
      </div>

      <div className="mb-8">
        <div className="flex items-center gap-2 mb-4">
          <Package className="h-5 w-5 text-gray-900" />
          <h2 className="text-lg font-semibold text-gray-900">Модули</h2>
        </div>
        <div className="bg-card rounded-xl shadow-sm border border-border overflow-hidden">
          <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-center px-6 py-3 text-xs font-semibold text-muted uppercase tracking-wider">Статус</th>
              </tr>
            </thead>
            <tbody>
              {modules.map((mod) => (
                <tr key={mod.id} className="border-b border-border last:border-0">
                  <td className="px-6 py-3 text-sm font-medium text-gray-900">{mod.name}</td>
                  <td className="px-6 py-3 text-sm text-gray-600">{mod.description}</td>
                  <td className="px-6 py-3 text-center">
                    {mod.enabled ? (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-success">
                        <CheckCircle className="h-3.5 w-3.5" />
                        Включён
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-xs font-medium text-muted">
                        Не включён
                      </span>
                    )}
                  </td>
                </tr>
              ))}
              {modules.length === 0 && (
                <tr>
                  <td colSpan={3} className="px-6 py-8 text-center text-sm text-muted">
                    Нет данных о модулях
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div>
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="h-5 w-5 text-gray-900" />
          <h2 className="text-lg font-semibold text-gray-900">Использование ресурсов</h2>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {usage.map((item) => {
            const percent = item.limit > 0 ? Math.round((item.current / item.limit) * 100) : 0;
            const barColor =
              percent >= 90 ? 'bg-error' : percent >= 70 ? 'bg-yellow-500' : 'bg-primary';
            return (
              <div
                key={item.label}
                className="bg-card rounded-xl p-5 shadow-sm border border-border"
              >
                <p className="text-sm text-muted mb-2">{item.label}</p>
                <p className="text-lg font-bold text-gray-900 mb-1">
                  {item.current.toLocaleString('ru-RU')}{' '}
                  <span className="text-sm font-normal text-muted">
                    / {item.limit > 0 ? item.limit.toLocaleString('ru-RU') : '\u221E'} {item.unit}
                  </span>
                </p>
                {item.limit > 0 && (
                  <div className="w-full bg-gray-200 rounded-full h-2 mt-2">
                    <div
                      className={`h-2 rounded-full ${barColor} transition-all`}
                      style={{ width: `${Math.min(percent, 100)}%` }}
                    />
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <RenewDialog
        open={showRenewDialog}
        onClose={() => setShowRenewDialog(false)}
        onRenewed={loadData}
        licenseInfo={{ type: licenseInfo.type, expiresAt: licenseInfo.expiresAt }}
      />
    </div>
  );
}
