import { useState } from 'react';
import {
  Alert,
  Badge,
  Button,
  Card,
  Spinner,
  useToast,
} from '@cameleer/design-system';
import { Copy, Eye, EyeOff } from 'lucide-react';
import { useTenantLicense } from '../../api/tenant-hooks';
import { UsageIndicator } from '../../components/UsageIndicator';
import { tierColor } from '../../utils/tier';
import styles from '../../styles/platform.module.css';

function daysColor(days: number): 'success' | 'warning' | 'error' | 'auto' {
  if (days <= 0) return 'error';
  if (days <= 30) return 'warning';
  return 'success';
}

export function TenantLicensePage() {
  const { data, isLoading, isError } = useTenantLicense();
  const { toast } = useToast();
  const [showToken, setShowToken] = useState(false);

  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 64 }}>
        <Spinner />
      </div>
    );
  }

  if (isError || !data) {
    return (
      <div style={{ padding: 24 }}>
        <Alert variant="error" title="Failed to load license">
          Could not fetch license data. Please refresh.
        </Alert>
      </div>
    );
  }

  async function handleCopy() {
    try {
      await navigator.clipboard.writeText(data!.token);
      toast({ title: 'Token copied to clipboard', variant: 'success' });
    } catch {
      toast({ title: 'Copy failed', variant: 'error' });
    }
  }

  const agentLimit = data.limits?.['agents'] ?? -1;
  const envLimit = data.limits?.['environments'] ?? -1;
  const retentionDays = data.limits?.['retentionDays'] ?? -1;

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <h1 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 600 }}>License</h1>
        <Badge label={data.tier} color={tierColor(data.tier)} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: 16 }}>
        {/* Validity card */}
        <Card title="Validity">
          <div className={styles.dividerList}>
            <div className={styles.kvRow}>
              <span className={styles.kvLabel}>Issued</span>
              <span className={styles.kvValue}>{new Date(data.issuedAt).toLocaleDateString()}</span>
            </div>
            <div className={styles.kvRow}>
              <span className={styles.kvLabel}>Expires</span>
              <span className={styles.kvValue}>{new Date(data.expiresAt).toLocaleDateString()}</span>
            </div>
            <div className={styles.kvRow}>
              <span className={styles.kvLabel}>Days remaining</span>
              <Badge
                label={data.daysRemaining <= 0 ? 'Expired' : `${data.daysRemaining}d`}
                color={daysColor(data.daysRemaining)}
              />
            </div>
          </div>
        </Card>

        {/* Features card */}
        <Card title="Features">
          <div className={styles.dividerList}>
            {Object.entries(data.features).map(([key, enabled]) => (
              <div key={key} className={styles.kvRow}>
                <span className={styles.kvLabel}>{key}</span>
                <Badge
                  label={enabled ? 'Enabled' : 'Disabled'}
                  color={enabled ? 'success' : 'auto'}
                />
              </div>
            ))}
            {Object.keys(data.features).length === 0 && (
              <p className={styles.description}>No feature flags configured.</p>
            )}
          </div>
        </Card>

        {/* Limits & Usage card */}
        <Card title="Limits & Usage">
          <div className={styles.dividerList}>
            <UsageIndicator used={0} limit={agentLimit} label="Agents" />
            <UsageIndicator used={0} limit={envLimit} label="Environments" />
            {retentionDays >= 0 && (
              <div className={styles.kvRow}>
                <span className={styles.kvLabel}>Data retention</span>
                <span className={styles.kvValue}>{retentionDays}d</span>
              </div>
            )}
          </div>
        </Card>
      </div>

      {/* License token card — full width */}
      <Card title="License Token">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <p className={styles.description}>
            This token is embedded in your Cameleer server configuration. Keep it secret.
          </p>
          <div className={styles.tokenBlock}>
            <code className={styles.tokenCode}>
              {showToken ? data.token : '••••••••••••••••••••••••••••••••'}
            </code>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="secondary" onClick={() => setShowToken((v) => !v)}>
              {showToken
                ? <><EyeOff size={14} style={{ marginRight: 6 }} />Hide</>
                : <><Eye size={14} style={{ marginRight: 6 }} />Show</>
              }
            </Button>
            <Button variant="secondary" onClick={handleCopy}>
              <Copy size={14} style={{ marginRight: 6 }} />
              Copy
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
}
