'use client';

import { Button, Dialog, Field, Input, Textarea, notify } from '@/components/ui';
import { BRAND_COLOR, defaultWelcomeBody, defaultWelcomeSubject } from '@/lib/email/welcome';
import { type WelcomeEmailState, sendWelcomeEmail } from '@/server/actions/welcomeEmail';
import { useRouter } from 'next/navigation';
import { useActionState, useEffect, useId, useState } from 'react';

interface Props {
  facilityId: string;
  facilityName: string;
  companyName: string;
  /** Pre-populated recipients (authorized representative + administrator). */
  defaultRecipients: string[];
}

function WelcomeDialog({
  facilityId,
  facilityName,
  companyName,
  defaultRecipients,
  onClose,
  onSent,
}: Props & { onClose: () => void; onSent: () => void }) {
  const uid = useId();
  const [state, action, pending] = useActionState(sendWelcomeEmail, {
    ok: false,
  } as WelcomeEmailState);
  const subject = defaultWelcomeSubject({ companyName, facilityName });
  const body = defaultWelcomeBody({ companyName, facilityName });

  // biome-ignore lint/correctness/useExhaustiveDependencies: fire once when the send succeeds
  useEffect(() => {
    if (!state.ok) return;
    if (state.status === 'sent') {
      notify('Welcome email sent.', { tone: 'success' });
    } else {
      notify('Welcome email saved. Delivery isn’t connected yet — set RESEND_API_KEY to send.', {
        tone: 'warning',
        ms: 7000,
      });
    }
    onSent();
  }, [state.ok]);

  return (
    <Dialog title="Send welcome email" onClose={onClose} className="max-w-xl">
      <form action={action} className="grid gap-3">
        <input type="hidden" name="facilityId" value={facilityId} />
        <Field
          label="Recipients"
          htmlFor={`${uid}-to`}
          hint="Comma-separated. Pre-filled with the authorized representative and administrator."
        >
          <Input
            id={`${uid}-to`}
            name="recipients"
            defaultValue={defaultRecipients.join(', ')}
            required
            placeholder="name@facility.com, name2@facility.com"
          />
        </Field>
        <Field label="Subject" htmlFor={`${uid}-subj`}>
          <Input
            id={`${uid}-subj`}
            name="subject"
            defaultValue={subject}
            required
            maxLength={300}
          />
        </Field>
        <Field
          label="Message"
          htmlFor={`${uid}-body`}
          hint={`Editable. Sent inside the ${companyName} branded template.`}
        >
          <Textarea
            id={`${uid}-body`}
            name="body"
            defaultValue={body}
            rows={12}
            required
            maxLength={20000}
            className="resize-y"
          />
        </Field>

        <div className="overflow-hidden rounded-lg border border-slate-200">
          <div
            style={{ background: BRAND_COLOR }}
            className="px-3 py-2 text-sm font-bold text-white"
          >
            {companyName}
          </div>
          <p className="px-3 py-2 text-xs text-slate-500">
            Your message is wrapped in the {companyName} branded template (header + footer) when
            sent.
          </p>
        </div>

        {state.error ? (
          <p role="alert" className="text-sm text-red-600">
            {state.error}
          </p>
        ) : null}

        <div className="flex justify-end gap-2">
          <Button type="button" variant="secondary" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit" loading={pending}>
            {pending ? 'Sending…' : 'Send welcome email'}
          </Button>
        </div>
      </form>
    </Dialog>
  );
}

/** "Send welcome email" — opens a modal pre-filled with branded copy + the intake's key contacts. */
export function WelcomeEmailButton(props: Props) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  return (
    <>
      <Button type="button" variant="secondary" onClick={() => setOpen(true)}>
        Send welcome email
      </Button>
      {open ? (
        <WelcomeDialog
          {...props}
          onClose={() => setOpen(false)}
          onSent={() => {
            setOpen(false);
            router.refresh();
          }}
        />
      ) : null}
    </>
  );
}
