'use client';

import * as ActionIcons from './Icons';

import { useEffect, useState } from 'react';
import { checkFeaturedAvailability, startCheckout } from '@/app/actions';
import { SubmitButton } from './Actions';
import { AlertIcon, CheckCircleIcon } from './Icons';

type Opt = { id: number; name: string };

/** Featured placement checkout: choose a page and who to feature; shows live slot availability */
export function FeaturedForm({ cities, practiceAreas, targets, price, enabled }: { cities: Opt[]; practiceAreas: Opt[]; targets: { kind: string; id: number; name: string }[]; price: number; enabled: boolean }) {
  const [cityId, setCity] = useState(0);
  const [areaId, setArea] = useState(0);
  const [room, setRoom] = useState<{ slots: number; taken: number; available: boolean } | null>(null);
  useEffect(() => {
    let live = true;
    setRoom(null);
    if (cityId && areaId) void checkFeaturedAvailability(cityId, areaId).then((r) => live && setRoom(r));
    return () => {
      live = false;
    };
  }, [cityId, areaId]);
  return (
    <form action={startCheckout} className="grid gap-4 p-5 text-sm sm:grid-cols-2">
      <input type="hidden" name="plan" value="featured" />
      <label className="block">
        <span className="field-label"><ActionIcons.MapPinIcon />City</span>
        <select name="cityId" required value={cityId || ''} onChange={(e) => setCity(Number(e.target.value))} className="field">
          <option value="">Choose…</option>
          {cities.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </label>
      <label className="block">
        <span className="field-label"><ActionIcons.ScaleIcon />Practice area</span>
        <select name="practiceAreaId" required value={areaId || ''} onChange={(e) => setArea(Number(e.target.value))} className="field">
          <option value="">Choose…</option>
          {practiceAreas.map((a) => (
            <option key={a.id} value={a.id}>
              {a.name}
            </option>
          ))}
        </select>
      </label>
      <label className="block sm:col-span-2">
        <span className="field-label"><ActionIcons.UsersIcon />Who to feature</span>
        <select name="target" required className="field" defaultValue="">
          <option value="">Choose…</option>
          {targets.map((x) => (
            <option key={`${x.kind}:${x.id}`} value={`${x.kind}:${x.id}`}>
              {x.kind === 'firm' ? `Firm — ${x.name}` : x.name}
            </option>
          ))}
        </select>
      </label>
      <div className="sm:col-span-2">
        {room &&
          (room.available ? (
            <p className="flex items-center gap-2 text-ledger">
              <CheckCircleIcon className="h-4 w-4" /> Available — {room.slots - room.taken} of {room.slots} sponsored slots free on this page
            </p>
          ) : (
            <p className="flex items-center gap-2 text-danger">
              <AlertIcon className="h-4 w-4" /> All {room.slots} sponsored slots on this page are taken
            </p>
          ))}
      </div>
      <div className="flex flex-wrap items-center gap-3 sm:col-span-2">
        <SubmitButton disabled={!enabled || (room !== null && !room.available)} pendingLabel="Opening checkout…" title={enabled ? undefined : 'Payments are not configured in this environment'}>
          <ActionIcons.DollarIcon />Continue to payment · ${price}/month
        </SubmitButton>
        <span className="text-xs text-muted">Shown with a “Sponsored” label above the organic list. It never changes anyone’s organic rank.</span>
      </div>
    </form>
  );
}
