'use client';

import { useState } from 'react';
import { useFormState, useFormStatus } from 'react-dom';
import type { ApiSubscriptionPlan, ApiSiteSettings } from '@/lib/backend-api';
import { subscribeToPlan, type SubscribeState } from '@/app/vendor/subscription/actions';
import { formatPrice, DEFAULT_CURRENCY } from '@/lib/site-settings';

const initialState: SubscribeState = undefined;

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending} className="btn-primary disabled:opacity-60">
      {pending ? 'Submitting…' : 'Subscribe'}
    </button>
  );
}

export function SubscriptionForm({
  plans,
  currency = DEFAULT_CURRENCY,
}: {
  plans: ApiSubscriptionPlan[];
  currency?: ApiSiteSettings['currency'];
}) {
  const [state, formAction] = useFormState(subscribeToPlan, initialState);
  const errors = state?.errors ?? {};
  const [selectedKey, setSelectedKey] = useState<string>(plans[0]?.key ?? '');
  const selectedPlan = plans.find((p) => p.key === selectedKey);
  const isPaidPlan = !!selectedPlan && selectedPlan.price > 0;

  return (
    <form action={formAction} className="space-y-5">
      {state?.success && (
        <div className="rounded-md border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
          {state.message}
        </div>
      )}

      {Object.keys(errors).length > 0 && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          <ul className="list-inside list-disc">
            {Object.values(errors).flat().map((error) => (
              <li key={error}>{error}</li>
            ))}
          </ul>
        </div>
      )}

      <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
        {plans.map((plan) => {
          const selected = selectedKey === plan.key;
          const disabled = plan.id === undefined;
          return (
            <label
              key={plan.key}
              className={`relative flex cursor-pointer flex-col rounded-lg border bg-white p-5 ${
                disabled ? 'cursor-not-allowed opacity-60' : ''
              } ${selected ? 'border-gold-500 shadow-lg ring-1 ring-gold-500' : plan.highlight ? 'border-gold-300' : 'border-navy-100'}`}
            >
              <input
                type="radio"
                name="plan_id"
                value={plan.id ?? ''}
                checked={selected}
                onChange={() => setSelectedKey(plan.key)}
                disabled={disabled}
                className="sr-only"
              />

              {plan.highlight && (
                <span className="absolute -top-3 left-1/2 -translate-x-1/2 rounded-full bg-gold-500 px-3 py-0.5 text-[10px] font-bold uppercase text-navy-800">
                  Popular
                </span>
              )}

              <span className="flex h-10 w-10 items-center justify-center rounded-full bg-beige text-gold-600">
                <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth={1.8}>
                  <path d="M3 21h18M5 21V9l7-6 7 6v12M9 21v-6h6v6" />
                </svg>
              </span>

              <h3 className="mt-3 font-serif text-base font-semibold text-navy-800">{plan.name}</h3>
              {plan.tagline && <p className="text-xs font-medium text-brown-500">{plan.tagline}</p>}
              {plan.description && <p className="mt-2 text-xs text-navy-600">{plan.description}</p>}

              <p className="mt-3">
                <span className="text-2xl font-bold text-navy-800">{plan.price > 0 ? formatPrice(plan.price, currency) : 'Free'}</span>
                {plan.price > 0 && <span className="text-xs text-navy-500"> {plan.period}</span>}
              </p>
              {!!plan.trial_days && plan.trial_days > 0 && (
                <p className="mt-1 inline-block w-fit rounded-full bg-green-50 px-2.5 py-0.5 text-[11px] font-semibold text-green-700">
                  {plan.trial_days}-day free trial
                </p>
              )}

              {plan.features.length > 0 && (
                <ul className="mt-4 flex-1 list-none space-y-2 text-xs text-navy-600">
                  <li className="text-[11px] font-semibold uppercase tracking-wide text-navy-400">Includes</li>
                  {plan.features.map((feature) => (
                    <li key={feature} className="flex items-start gap-2">
                      <span className="mt-0.5 text-gold-600" aria-hidden="true">&#10003;</span>
                      <span>{feature}</span>
                    </li>
                  ))}
                </ul>
              )}

              <p
                className={`mt-4 rounded-md py-2 text-center text-sm font-semibold ${
                  selected ? 'bg-gold-500 text-navy-800' : 'border border-navy-100 text-navy-600'
                }`}
              >
                {selected ? 'Selected' : 'Select This Plan'}
              </p>
            </label>
          );
        })}
      </div>

      {isPaidPlan && (
        <div className="space-y-4 rounded-md border border-navy-100 bg-beige p-4">
          <div>
            <label className="block text-sm font-semibold text-navy-800">Your Bank Name</label>
            <input
              type="text"
              name="bank_name"
              required
              className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-navy-800">Transaction Reference</label>
            <input
              type="text"
              name="transaction_reference"
              required
              className="mt-1.5 w-full rounded-md border-navy-100 text-sm focus:border-gold-500 focus:ring-gold-500"
            />
          </div>
          <div>
            <label className="block text-sm font-semibold text-navy-800">Payment Receipt (optional)</label>
            <input type="file" name="receipt" accept="image/jpeg,image/png,application/pdf" className="mt-1.5 w-full text-sm text-navy-600" />
          </div>
        </div>
      )}

      <SubmitButton />
    </form>
  );
}
