'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/lib/hooks/useAuth';
import { authApi } from '@/lib/api/auth';
import type { SubscriptionAlertData } from '@/types';

export default function SubscriptionsSettingsPage() {
  const { currentOrganization } = useAuth();
  const router = useRouter();
  const [alert, setAlert] = useState<SubscriptionAlertData | null>(null);

  useEffect(() => {
    if (currentOrganization && !currentOrganization.isOwner) {
      router.replace('/today');
    }
  }, [currentOrganization, router]);

  useEffect(() => {
    if (!currentOrganization?.isOwner) return;
    void authApi.getSubscriptionAlert().then((r) => {
      if (r.success) setAlert(r.data);
    });
  }, [currentOrganization?.id, currentOrganization?.isOwner]);

  if (!currentOrganization) {
    return (
      <p className="text-text-secondary text-sm">Loading...</p>
    );
  }

  if (!currentOrganization.isOwner) {
    return (
      <p className="text-text-secondary text-sm">Redirecting...</p>
    );
  }

  const plan = currentOrganization.plan;
  const maxUsers = plan?.maxUsers;

  return (
    <div className="max-w-xl space-y-6">
      <div>
        <Link
          href="/today"
          className="text-sm text-primary hover:opacity-90"
        >
          ← Back to app
        </Link>
        <h1 className="text-2xl font-semibold text-text-primary mt-4">Subscriptions</h1>
        <p className="text-text-secondary text-sm mt-2">
          Your DyoLink workspace plan and seats for{' '}
          <span className="text-text-primary font-medium">{currentOrganization.name}</span>.
          Clinic and lab income tracking stays under the sidebar{' '}
          <span className="text-text-primary">Billing</span> tab.
        </p>
      </div>

      <div className="surface-card p-6 space-y-4">
        <div className="flex flex-wrap gap-4 justify-between">
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">Current plan</p>
            <p className="text-lg font-medium text-text-primary capitalize">
              {plan?.name ?? '—'}
            </p>
          </div>
          {typeof maxUsers === 'number' && maxUsers < 999999 && (
            <div>
              <p className="text-xs text-text-muted uppercase tracking-wide">Seats (this org)</p>
              <p className="text-lg font-medium text-text-primary">
                {alert?.seatsUsed ?? '—'} / {maxUsers}
              </p>
            </div>
          )}
        </div>

        {alert?.showWarning && (
          <div className="text-sm text-text-secondary space-y-1">
            {alert.trialExpired && (
              <p>Trial period has ended. Choose a plan when checkout is available.</p>
            )}
            {!alert.trialExpired && alert.trialEndingSoon && (
              <p>
                Trial ends in {alert.daysUntilTrialEnd ?? '—'} day(s).
              </p>
            )}
            {!alert.trialExpired && !alert.trialEndingSoon && alert.seatsLow && (
              <p>Seat usage is high for this organization.</p>
            )}
          </div>
        )}

        <p className="text-sm text-text-secondary">
          Payment and plan upgrades will connect here. The warning on the settings
          icon is only shown to workspace owners when seats are low or the trial window
          is ending.
        </p>
      </div>
    </div>
  );
}
