'use client';

import React from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * License & Regulatory Permits Management - 牌照与监管许可管理
 */

interface LicenseData {
  stats: { label: string; value: string; color: string }[];
  licenses: { id: string; name: string; jurisdiction: string; regBody: string; status: string; issueDate: string; expiryDate: string }[];
  regulatoryBodies: { name: string; fullName: string; scope: string; licenses: number }[];
  renewalAlerts: { license: string; expiryDate: string; daysRemaining: number; urgency: string }[];
  activeLicenseCount: number;
  jurisdictionsCovered: number;
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

const getLicenseStatusStyle = (status: string) => {
  switch (status) {
    case 'active': return { background: 'var(--color-success-light)', color: 'var(--color-success)' };
    case 'applying': return { background: 'var(--color-info-light)', color: 'var(--color-info)' };
    case 'renewal': return { background: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'expiring': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    case 'expired': return { background: 'var(--color-gray-100)', color: 'var(--color-error)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

const getLicenseStatusLabel = (status: string) => {
  const map: Record<string, () => string> = {
    active: () => t('license_status_active'),
    applying: () => t('license_status_applying'),
    renewal: () => t('license_status_renewal'),
    expiring: () => t('license_status_expiring'),
  };
  return map[status]?.() ?? status;
};

const getUrgencyStyle = (urgency: string) => {
  switch (urgency) {
    case 'critical': return { background: 'var(--color-error)', color: 'white' };
    case 'high': return { background: 'var(--color-error-light)', color: 'var(--color-error)' };
    case 'medium': return { background: 'var(--color-warning-light)', color: 'var(--color-warning)' };
    case 'low': return { background: 'var(--color-success-light)', color: 'var(--color-success)' };
    default: return { background: 'var(--color-gray-100)', color: 'var(--color-text-tertiary)' };
  }
};

export const LicenseManagementPage: React.FC = () => {
  const { data, isLoading, error } = useApi<LicenseData>('/api/v1/admin/compliance/licenses');

  if (error) return <div style={loadingBox}>Error: {error.message}</div>;
  if (isLoading) return <div style={loadingBox}>Loading...</div>;

  const licenseStats = data?.stats ?? [];
  const licenses = data?.licenses ?? [];
  const regulatoryBodies = data?.regulatoryBodies ?? [];
  const renewalAlerts = data?.renewalAlerts ?? [];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)' }}>{t('license_title')}</h1>
        <button style={{
          padding: '8px 16px', border: 'none', borderRadius: 'var(--radius-full)',
          background: 'var(--color-primary)', color: 'white', cursor: 'pointer', font: 'var(--text-label-sm)',
        }}>{t('license_new')}</button>
      </div>

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {licenseStats.map(s => (
          <div key={s.label} style={{
            background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)', padding: 20,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 8 }}>{s.label}</div>
            <div style={{ font: 'var(--text-h1)', color: s.color }}>{s.value}</div>
          </div>
        ))}
      </div>

      {/* License Table */}
      <div style={{
        background: 'var(--color-surface)', borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)', overflow: 'hidden', marginBottom: 24,
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--color-border-light)' }}>
          <h2 style={{ font: 'var(--text-h2)', color: 'var(--color-text-primary)' }}>{t('license_list')}</h2>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('license_th_id'), t('license_th_name'), t('license_th_jurisdiction'), t('license_th_reg_body'), t('license_th_issue_date'), t('license_th_expiry_date'), t('license_th_status'), t('actions')].map(h => (
                <th key={h} style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '10px 14px', textAlign: 'left' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {licenses.map(l => (
              <tr key={l.id} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                <td style={{ font: 'var(--text-body-sm)', fontFamily: 'var(--font-family-mono)', padding: '10px 14px' }}>{l.id}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-primary)', fontWeight: 500 }}>{l.name}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-secondary)' }}>{l.jurisdiction}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px', borderRadius: 'var(--radius-full)',
                    background: 'var(--color-info-light)', color: 'var(--color-info)',
                    font: 'var(--text-caption)',
                  }}>{l.regBody}</span>
                </td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{l.issueDate}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px', color: 'var(--color-text-tertiary)' }}>{l.expiryDate}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                    ...getLicenseStatusStyle(l.status),
                  }}>{getLicenseStatusLabel(l.status)}</span>
                </td>
                <td style={{ padding: '10px 14px' }}>
                  <button style={{ padding: '4px 12px', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', background: 'none', cursor: 'pointer', font: 'var(--text-caption)', color: 'var(--color-primary)' }}>{t('details')}</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
        {/* Regulatory Body Mapping */}
        <div style={{ background: 'var(--color-surface)', borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border-light)', padding: 20 }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 16 }}>{t('license_reg_body_mapping')}</h2>
          {regulatoryBodies.map((rb, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid var(--color-border-light)' }}>
              <div style={{
                width: 40, height: 40, borderRadius: 'var(--radius-sm)', marginRight: 12,
                background: 'var(--color-primary-light)', color: 'var(--color-primary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                font: 'var(--text-label-sm)', fontWeight: 700, flexShrink: 0,
              }}>
                {rb.name.slice(0, 3)}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-label)', color: 'var(--color-text-primary)' }}>{rb.name}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{rb.fullName}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-secondary)', marginTop: 2 }}>{rb.scope}</div>
              </div>
              <span style={{
                padding: '2px 10px', borderRadius: 'var(--radius-full)',
                background: rb.licenses > 0 ? 'var(--color-success-light)' : 'var(--color-gray-100)',
                color: rb.licenses > 0 ? 'var(--color-success)' : 'var(--color-text-tertiary)',
                font: 'var(--text-caption)',
              }}>
                {rb.licenses > 0 ? `${rb.licenses} ${t('license_unit')}` : t('not_applied')}
              </span>
            </div>
          ))}
        </div>

        {/* Renewal Alerts */}
        <div style={{ background: 'var(--color-surface)', borderRadius: 'var(--radius-md)', border: '1px solid var(--color-border-light)', padding: 20 }}>
          <h2 style={{ font: 'var(--text-h2)', marginBottom: 16 }}>{t('license_renewal_alerts')}</h2>
          {renewalAlerts.map((alert, i) => (
            <div key={i} style={{
              padding: 16, marginBottom: 12,
              borderRadius: 'var(--radius-sm)',
              border: `1px solid ${alert.urgency === 'critical' ? 'var(--color-error)' : 'var(--color-border-light)'}`,
              background: alert.urgency === 'critical' ? 'var(--color-error-light)' : 'var(--color-surface)',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <span style={{ font: 'var(--text-label)', color: 'var(--color-text-primary)' }}>{alert.license}</span>
                <span style={{
                  padding: '2px 8px', borderRadius: 'var(--radius-full)', font: 'var(--text-caption)', fontWeight: 600,
                  ...getUrgencyStyle(alert.urgency),
                }}>
                  {alert.urgency === 'critical' ? t('urgency_critical') : alert.urgency === 'high' ? t('urgency_high') : alert.urgency === 'medium' ? t('urgency_medium') : t('urgency_low')}
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{t('expiry_date')}: {alert.expiryDate}</span>
                <span style={{
                  font: 'var(--text-label-sm)',
                  color: alert.daysRemaining <= 30 ? 'var(--color-error)' : alert.daysRemaining <= 90 ? 'var(--color-warning)' : 'var(--color-text-secondary)',
                }}>
                  {t('remaining_days').replace('{0}', String(alert.daysRemaining))}
                </span>
              </div>
              {alert.urgency === 'critical' && (
                <button style={{
                  marginTop: 10, padding: '6px 14px', width: '100%',
                  border: 'none', borderRadius: 'var(--radius-sm)',
                  background: 'var(--color-error)', color: 'white',
                  cursor: 'pointer', font: 'var(--text-label-sm)',
                }}>{t('renew_now')}</button>
              )}
            </div>
          ))}
          <div style={{ marginTop: 16, padding: 12, background: 'var(--color-gray-50)', borderRadius: 'var(--radius-sm)' }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-secondary)' }}>
              {data?.activeLicenseCount ?? 0} {t('license_jurisdictions_covered').replace('{0}', String(data?.jurisdictionsCovered ?? 0))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
