'use client';

import { use, useEffect, useState } from 'react';
import { CheckCircle2, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { CountryCombobox } from '@/components/shared/country-combobox';
import { PhoneInput, type PhoneInputValue } from '@/components/shared/phone-input';
import { BrandedAuthShell } from '@/components/shared/branded-auth-shell';
import type { CountryCode } from '@/lib/i18n/countries';

interface PrefillData {
  token: { expiresAt: string; consumed: boolean };
  port: {
    name: string;
    logoUrl: string | null;
    backgroundUrl: string | null;
  };
  client: {
    fullName: string;
    streetAddress: string | null;
    city: string | null;
    subdivisionIso: string | null;
    postalCode: string | null;
    country: string | null;
    primaryEmail: string | null;
    primaryPhone: string | null;
    primaryPhoneCountry: string | null;
  };
  yacht: {
    name: string | null;
    lengthFt: string | null;
    widthFt: string | null;
    draftFt: string | null;
  } | null;
}

interface PageProps {
  params: Promise<{ token: string }>;
}

export default function SupplementalInfoPage({ params }: PageProps) {
  const { token } = use(params);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<PrefillData | null>(null);

  // Form fields
  const [fullName, setFullName] = useState('');
  const [address, setAddress] = useState('');
  const [city, setCity] = useState('');
  const [region, setRegion] = useState('');
  const [postalCode, setPostalCode] = useState('');
  const [country, setCountry] = useState<CountryCode | null>(null);
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState<PhoneInputValue | null>(null);
  const [yachtName, setYachtName] = useState('');
  const [yachtLength, setYachtLength] = useState('');
  const [yachtWidth, setYachtWidth] = useState('');
  const [yachtDraft, setYachtDraft] = useState('');

  useEffect(() => {
    let cancelled = false;
    async function load() {
      try {
        const res = await fetch(`/api/public/supplemental-info/${token}`);
        if (!res.ok) {
          setError(
            res.status === 404
              ? 'This link is no longer valid. It may have expired or already been used.'
              : 'Could not load this form. Please try again later.',
          );
          return;
        }
        const payload = (await res.json()) as { data: PrefillData };
        if (cancelled) return;
        setData(payload.data);
        setFullName(payload.data.client.fullName ?? '');
        setAddress(payload.data.client.streetAddress ?? '');
        setCity(payload.data.client.city ?? '');
        setRegion(payload.data.client.subdivisionIso ?? '');
        setPostalCode(payload.data.client.postalCode ?? '');
        setCountry((payload.data.client.country as CountryCode | null) ?? null);
        setEmail(payload.data.client.primaryEmail ?? '');
        if (payload.data.client.primaryPhone) {
          setPhone({
            e164: payload.data.client.primaryPhone,
            country: (payload.data.client.primaryPhoneCountry as CountryCode | null) ?? 'US',
          });
        }
        if (payload.data.yacht) {
          setYachtName(payload.data.yacht.name ?? '');
          setYachtLength(payload.data.yacht.lengthFt ?? '');
          setYachtWidth(payload.data.yacht.widthFt ?? '');
          setYachtDraft(payload.data.yacht.draftFt ?? '');
        }
      } catch {
        setError('Could not load this form. Please check your connection and try again.');
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, [token]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!fullName.trim()) {
      toast.error('Please enter your full name.');
      return;
    }
    setSubmitting(true);
    try {
      const res = await fetch(`/api/public/supplemental-info/${token}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fullName: fullName.trim(),
          address: address.trim() || null,
          city: city.trim() || null,
          subdivisionIso: region.trim() || null,
          postalCode: postalCode.trim() || null,
          country: country ?? null,
          email: email.trim() || null,
          phoneE164: phone?.e164 ?? null,
          phoneCountry: phone?.country ?? null,
          yachtName: yachtName.trim() || null,
          yachtLengthFt: parseFloat(yachtLength) || null,
          yachtWidthFt: parseFloat(yachtWidth) || null,
          yachtDraftFt: parseFloat(yachtDraft) || null,
        }),
      });
      if (!res.ok) {
        const payload = (await res.json().catch(() => ({}))) as { error?: { message?: string } };
        toast.error(payload.error?.message ?? 'Failed to submit. Please try again.');
        return;
      }
      setSubmitted(true);
    } catch {
      toast.error('Failed to submit. Please check your connection.');
    } finally {
      setSubmitting(false);
    }
  }

  // Branding prop fed into BrandedAuthShell. Falls back to nulls until
  // `data` lands; once it lands the shell re-renders with the resolved
  // port logo + backdrop.
  const branding = data
    ? {
        logoUrl: data.port.logoUrl,
        backgroundUrl: data.port.backgroundUrl,
        appName: data.port.name,
      }
    : undefined;

  if (loading) {
    return (
      <BrandedAuthShell width="md" branding={branding}>
        <div role="status" aria-live="polite" className="flex items-center justify-center py-8">
          <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          <span className="sr-only">Loading</span>
        </div>
      </BrandedAuthShell>
    );
  }

  if (error) {
    return (
      <BrandedAuthShell width="md" branding={branding}>
        <div role="alert" aria-live="assertive" className="text-center space-y-2 py-6">
          <p className="text-sm text-muted-foreground">{error}</p>
        </div>
      </BrandedAuthShell>
    );
  }

  if (submitted) {
    return (
      <BrandedAuthShell width="md" branding={branding}>
        <div className="text-center space-y-3 py-6">
          <CheckCircle2 className="h-10 w-10 text-emerald-600 mx-auto" />
          <h1 className="text-lg font-semibold">Thanks, got it</h1>
          <p className="text-sm text-muted-foreground">
            Your details have been sent to the team at {data?.port.name ?? 'the marina'}. Watch your
            inbox for your EOI document shortly.
          </p>
        </div>
      </BrandedAuthShell>
    );
  }

  return (
    <BrandedAuthShell width="md" branding={branding}>
      <form onSubmit={onSubmit} className="space-y-6">
        <div className="space-y-2 text-center">
          <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
            {data?.port.name}
          </p>
          <h1 className="text-xl font-semibold">A few details before we draft your EOI</h1>
          <p className="text-sm text-muted-foreground">
            We&apos;ve pre-filled what we have on file. Please review, correct anything that&apos;s
            wrong, and add what&apos;s missing. Submissions go straight to the team handling your
            application.
          </p>
          {data?.token.consumed ? (
            <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
              You&apos;ve submitted this form before. Feel free to update any details. Changes
              overwrite the previous submission.
            </div>
          ) : null}
        </div>

        <fieldset className="space-y-4">
          <legend className="mb-2 px-1 text-sm font-semibold text-foreground">Your details</legend>
          <div className="space-y-1.5">
            <Label htmlFor="fullName">Full name</Label>
            <Input
              id="fullName"
              value={fullName}
              onChange={(e) => setFullName(e.target.value)}
              required
            />
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@example.com"
            />
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="phone">Phone</Label>
            <PhoneInput id="phone" value={phone} onChange={setPhone} placeholder="Phone number" />
            <p className="text-xs text-muted-foreground">
              Use a different number than the one you signed up with if you&apos;d prefer to be
              reached there instead.
            </p>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="address">Street address</Label>
            <Textarea
              id="address"
              rows={2}
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              placeholder="Apartment, suite, building, street"
            />
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="city">City</Label>
              <Input id="city" value={city} onChange={(e) => setCity(e.target.value)} />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="postalCode">Postal code</Label>
              <Input
                id="postalCode"
                value={postalCode}
                onChange={(e) => setPostalCode(e.target.value)}
              />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="region">Region / state</Label>
              <Input
                id="region"
                value={region}
                onChange={(e) => setRegion(e.target.value)}
                placeholder="Optional"
              />
            </div>
            <div className="space-y-1.5">
              <Label>Country</Label>
              <CountryCombobox value={country} onChange={(c) => setCountry(c ?? null)} clearable />
            </div>
          </div>
        </fieldset>

        <fieldset className="space-y-4">
          <legend className="mb-2 px-1 text-sm font-semibold text-foreground">
            Your yacht (optional)
          </legend>
          <div className="space-y-1.5">
            <Label htmlFor="yachtName">Yacht name</Label>
            <Input
              id="yachtName"
              value={yachtName}
              onChange={(e) => setYachtName(e.target.value)}
              placeholder="Name on the hull"
            />
          </div>

          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-1.5">
              <Label htmlFor="length">Length (ft)</Label>
              <Input
                id="length"
                type="number"
                step="0.1"
                value={yachtLength}
                onChange={(e) => setYachtLength(e.target.value)}
                placeholder="0"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="width">Width (ft)</Label>
              <Input
                id="width"
                type="number"
                step="0.1"
                value={yachtWidth}
                onChange={(e) => setYachtWidth(e.target.value)}
                placeholder="0"
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="draft">Draft (ft)</Label>
              <Input
                id="draft"
                type="number"
                step="0.1"
                value={yachtDraft}
                onChange={(e) => setYachtDraft(e.target.value)}
                placeholder="0"
              />
            </div>
          </div>
        </fieldset>

        <Button type="submit" className="w-full" disabled={submitting}>
          {submitting ? 'Submitting…' : 'Submit'}
        </Button>

        <p className="text-center text-xs text-muted-foreground">
          This link is private to you. You can come back and update your details until it expires.
        </p>
      </form>
    </BrandedAuthShell>
  );
}
