'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/subscription';

const PLAN_OPTIONS = [
  { id: 'solo', name: 'Solo', maxUsers: 1, price: 19 },
  { id: 'small', name: 'Small', maxUsers: 5, price: 49 },
  { id: 'medium', name: 'Medium', maxUsers: 10, price: 89 },
  { id: 'large', name: 'Large', maxUsers: 15, price: 129 },
  { id: 'enterprise', name: 'Enterprise', maxUsers: null, price: 199 },
] as const;

export default function SubscriptionsSettingsPage() {
  const { currentOrganization } = useAuth();
  const router = useRouter();
  const [alert, setAlert] = useState<SubscriptionAlertData | null>(null);
  const [selectedPlanId, setSelectedPlanId] = useState<string>(PLAN_OPTIONS[0].id);
  const [purchaseNotice, setPurchaseNotice] = useState<string | 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 hasActiveSubscription = Boolean(plan);
  const selectedPlan = PLAN_OPTIONS.find((option) => option.id === selectedPlanId);
  const maxUsers = plan?.maxUsers;
  const isUnlimited = typeof maxUsers === 'number' && maxUsers >= 999999;
  const seatsUsed = alert?.seatsUsed;
  const seatsRemaining =
    typeof seatsUsed === 'number' && typeof maxUsers === 'number' && !isUnlimited
      ? Math.max(0, maxUsers - seatsUsed)
      : null;
  const daysUntilPlanEnd = alert?.daysUntilPlanEnd ?? null;
  const planDayTone =
    daysUntilPlanEnd == null
      ? 'text-text-primary'
      : daysUntilPlanEnd > 20
        ? 'text-emerald-400'
        : daysUntilPlanEnd >= 10
          ? 'text-amber-300'
          : 'text-red-400';

  return (
    <div className="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">
        {!hasActiveSubscription && (
          <div className="rounded-[var(--radius-md)] border border-amber-500/30 bg-amber-500/10 p-4">
            <p className="text-sm text-amber-200">
              This organization has no active subscription. Select a plan below to start
              the purchase process.
            </p>
          </div>
        )}

        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
          <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>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">Plan price</p>
            <p className="text-lg font-medium text-text-primary">
              {typeof plan?.price === 'number' ? `$${plan.price}` : '—'}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">Seats used</p>
            <p className="text-lg font-medium text-text-primary">
              {typeof seatsUsed === 'number' ? seatsUsed : '—'}
              {typeof maxUsers === 'number' ? ` / ${isUnlimited ? 'Unlimited' : maxUsers}` : ''}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">Seats remaining</p>
            <p className="text-lg font-medium text-text-primary">
              {isUnlimited ? 'Unlimited' : seatsRemaining ?? '—'}
            </p>
          </div>
          <div>
            <p className="text-xs text-text-muted uppercase tracking-wide">Days remaining</p>
            <p className={`text-lg font-medium ${planDayTone}`}>
              {daysUntilPlanEnd ?? '—'}
            </p>
          </div>
        </div>

        {alert?.showWarning && (
          <div className="text-sm text-text-secondary space-y-1">
            {alert.noActiveSubscription && (
              <p>No active subscription for this organization.</p>
            )}
            {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>
        )}

        <div className="space-y-3 pt-2">
          <p className="text-sm text-text-secondary">
            Choose a plan to continue. Purchase integration is not active yet, so this
            currently prepares the selection step only.
          </p>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {PLAN_OPTIONS.map((option) => {
              const selected = selectedPlanId === option.id;
              return (
                <button
                  key={option.id}
                  type="button"
                  onClick={() => setSelectedPlanId(option.id)}
                  className={`rounded-[var(--radius-md)] border p-4 text-left transition-colors ${
                    selected
                      ? 'border-primary/70 bg-primary-soft'
                      : 'border-border hover:border-border-strong'
                  }`}
                >
                  <p className="text-base font-medium text-text-primary">{option.name}</p>
                  <p className="text-sm text-text-secondary mt-1">
                    {option.maxUsers == null ? 'Unlimited seats' : `${option.maxUsers} seats`}
                  </p>
                  <p className="text-sm text-text-secondary mt-1">${option.price} / month</p>
                </button>
              );
            })}
          </div>
          <button
            type="button"
            className="inline-flex items-center justify-center rounded-[var(--radius-md)] bg-primary px-4 py-2 text-sm font-medium text-white hover:opacity-90 disabled:opacity-60"
            onClick={() => {
              const selectedPlanLabel = selectedPlan?.name ?? 'the selected plan';
              setPurchaseNotice(
                `Purchase flow will be enabled soon. ${selectedPlanLabel} is selected and ready for checkout setup.`,
              );
            }}
          >
            Start purchase process
          </button>
          {purchaseNotice && (
            <div className="rounded-[var(--radius-md)] border border-emerald-500/30 bg-emerald-500/10 px-4 py-3">
              <p className="text-sm text-emerald-200">{purchaseNotice}</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
