'use client';

/**
 * Provision a venue in one go: venue + first room + OWNER user (temporary password shown once) +
 * a TRIALING entitlement. The join code follows the name until the admin edits it; the server
 * re-checks uniqueness and picks the next free suggestion if the automatic one is taken.
 */
import { useState } from 'react';
import { Field, Input, Select } from '@/components/ui/Field';
import { fieldError, type ActionResult } from '@/components/host/action-result';
import { FormMessage, SubmitButton, useActionForm } from '@/components/host/client';
import { formatPrice } from '@/components/host/format';
import { joinCodeCandidates, slugify } from '@/lib/auth/venue-codes';

export function CreateVenueForm({
  action,
  plans,
  timezones,
}: {
  action: (prev: ActionResult, formData: FormData) => Promise<ActionResult>;
  plans: { key: string; name: string; priceCents: number; interval: string }[];
  timezones: readonly { value: string; label: string }[];
}) {
  const { result, pending, onSubmit } = useActionForm(action);
  const [name, setName] = useState('');
  const [joinCode, setJoinCode] = useState('');
  const [codeEdited, setCodeEdited] = useState(false);
  // Deterministic first suggestion (the distinctive word of the name); random fallbacks happen server-side.
  const suggested = name.trim() ? (joinCodeCandidates(name, 1, () => 0)[0] ?? '') : '';
  const shownCode = codeEdited ? joinCode : suggested;
  const created = result.status === 'success';

  return (
    <form onSubmit={onSubmit} className="flex flex-col gap-8">
      <input type="hidden" name="joinCodeAuto" value={codeEdited ? '0' : '1'} />
      <FormMessage result={result} />
      <fieldset disabled={created} className="flex flex-col gap-8 disabled:opacity-60">
        <section className="grid gap-5 md:grid-cols-2">
          <h2 className="font-display text-lg font-semibold md:col-span-2">Venue</h2>
          <Field label="Venue name" required error={fieldError(result, 'name')}>
            <Input name="name" value={name} onChange={(e) => setName(e.target.value)} maxLength={80} required placeholder="The Anchor & Oar" />
          </Field>
          <Field label="URL slug" optional error={fieldError(result, 'slug')} hint="Leave blank to generate it from the name.">
            <Input name="slug" maxLength={48} placeholder={name ? slugify(name) : 'the-anchor-and-oar'} pattern="[a-z0-9]+(-[a-z0-9]+)*" />
          </Field>
          <Field label="Join code" required error={fieldError(result, 'joinCode')} hint="4–8 letters or digits, printed on the QR poster. Suggested from the name — edit to choose your own.">
            <Input
              name="joinCode"
              value={shownCode}
              onChange={(e) => {
                setCodeEdited(true);
                setJoinCode(e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8));
              }}
              required
              minLength={4}
              maxLength={8}
              autoCapitalize="characters"
              spellCheck={false}
              className="num font-semibold tracking-[0.12em]"
            />
          </Field>
          <Field label="Time zone" required error={fieldError(result, 'timezone')}>
            <Select name="timezone" defaultValue="America/New_York" required>
              {timezones.map((tz) => (
                <option key={tz.value} value={tz.value}>
                  {tz.label}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Address" optional error={fieldError(result, 'address')} className="md:col-span-2">
            <Input name="address" maxLength={200} autoComplete="off" placeholder="123 Main St, Huntington, NY" />
          </Field>
          <Field label="First room" required error={fieldError(result, 'roomName')} hint="Rooms are screens with their own game, e.g. Main Bar, Patio.">
            <Input name="roomName" defaultValue="Main Bar" maxLength={60} required />
          </Field>
        </section>

        <section className="grid gap-5 md:grid-cols-2">
          <h2 className="font-display text-lg font-semibold md:col-span-2">Owner account</h2>
          <Field label="Owner name" required error={fieldError(result, 'ownerName')}>
            <Input name="ownerName" maxLength={80} required autoComplete="off" />
          </Field>
          <Field label="Owner email" required error={fieldError(result, 'ownerEmail')} hint="They sign in at /host/login. A temporary password is shown once after creation.">
            <Input name="ownerEmail" type="email" maxLength={254} required autoComplete="off" />
          </Field>
        </section>

        <section className="grid gap-5 md:grid-cols-2">
          <h2 className="font-display text-lg font-semibold md:col-span-2">Pilot plan</h2>
          <Field label="Plan" required error={fieldError(result, 'planKey')}>
            <Select name="planKey" defaultValue={plans.find((p) => p.key === 'pro')?.key ?? plans[0]?.key} required>
              {plans.map((p) => (
                <option key={p.key} value={p.key}>
                  {p.name} · {formatPrice(p.priceCents, p.interval)}
                </option>
              ))}
            </Select>
          </Field>
          <Field label="Trial length (days)" required error={fieldError(result, 'trialDays')} hint="Starts as TRIALING. No billing is connected yet.">
            <Input name="trialDays" type="number" inputMode="numeric" min={0} max={365} defaultValue={30} required />
          </Field>
        </section>
      </fieldset>

      {!created && (
        <div className="border-t border-line/70 pt-6">
          <SubmitButton size="lg" pending={pending} pendingLabel="Creating venue…">
            Create venue
          </SubmitButton>
        </div>
      )}
    </form>
  );
}
