/**
 * Create-tenant dialog. Renders as a Radix Dialog triggered by a
 * Button. Uses react-hook-form for the form state. The form
 * fields are validated client-side (zod) AND server-side; the
 * server returns 400 on any validation error.
 *
 * Renders nothing if the user lacks the create-tenant permission
 * (super_admin only). The button is hidden too.
 */

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Plus } from 'lucide-react';
import { toast } from 'sonner';
import { useNavigate } from 'react-router-dom';

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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';

import { getErrorMessage, useCreateTenant } from './api';
import type { CreateTenantInput as CreateTenantBody } from './types';

const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]$/;

const formSchema = z.object({
  slug: z
    .string()
    .min(2, 'Slug must be 2–64 characters')
    .max(64, 'Slug must be 2–64 characters')
    .regex(SLUG_RE, 'Lowercase letters, digits, and dashes only'),
  display_name: z.string().min(1, 'Display name is required'),
  contact_email: z.string().email('Enter a valid email'),
  rate_limit_per_sec: z
    .number({ invalid_type_error: 'Enter a number' })
    .int('Whole number only')
    .min(1, 'Must be at least 1')
    .max(1_000_000, 'Must be at most 1,000,000'),
  fcm_shared: z.boolean(),
});

type FormValues = z.infer<typeof formSchema>;

export function CreateTenantDialog() {
  const [open, setOpen] = useState(false);
  const navigate = useNavigate();
  const create = useCreateTenant();

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      slug: '',
      display_name: '',
      contact_email: '',
      rate_limit_per_sec: 10000,
      fcm_shared: true,
    },
  });

  // Reset form when the dialog opens. The reset is gated on
  // `open` so it only fires on the close->open transition.
  useEffect(() => {
    if (open) {
      form.reset();
    }
  }, [open, form]);

  const onSubmit = form.handleSubmit(async (values) => {
    const body: CreateTenantBody = {
      slug: values.slug.trim(),
      display_name: values.display_name.trim(),
      contact_email: values.contact_email.trim(),
      rate_limit_per_sec: values.rate_limit_per_sec,
      fcm_shared: values.fcm_shared,
    };
    try {
      const created = await create.mutateAsync(body);
      toast.success(`Created ${created.display_name}`);
      setOpen(false);
      // Land the operator on the new tenant's detail page so
      // they can immediately wire up users and sources.
      navigate(`/companies/${created.id}`);
    } catch (err) {
      const msg = getErrorMessage(err);
      toast.error(msg);
      // Surface duplicate-slug as a field error so the operator
      // sees it next to the input, not just in a toast.
      if (msg.toLowerCase().includes('slug')) {
        form.setError('slug', { message: msg });
      }
    }
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>
          <Plus className="h-4 w-4" />
          New company
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>New company</DialogTitle>
          <DialogDescription>
            The slug becomes part of every event this tenant sends
            (and shows up in the audit log). Choose carefully — it
            cannot be changed after creation.
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={onSubmit} className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="slug">Slug</Label>
              <Input
                id="slug"
                placeholder="acme-corp"
                autoComplete="off"
                {...form.register('slug')}
                aria-invalid={Boolean(form.formState.errors.slug)}
              />
              {form.formState.errors.slug ? (
                <p className="text-xs text-destructive">
                  {form.formState.errors.slug.message}
                </p>
              ) : (
                <p className="text-xs text-muted-foreground">
                  2–64 chars, lowercase + digits + dashes.
                </p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="rate_limit_per_sec">Rate limit (events/sec)</Label>
              <Input
                id="rate_limit_per_sec"
                type="number"
                min={1}
                max={1_000_000}
                {...form.register('rate_limit_per_sec', { valueAsNumber: true })}
                aria-invalid={Boolean(form.formState.errors.rate_limit_per_sec)}
              />
              {form.formState.errors.rate_limit_per_sec ? (
                <p className="text-xs text-destructive">
                  {form.formState.errors.rate_limit_per_sec.message}
                </p>
              ) : null}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="display_name">Display name</Label>
            <Input
              id="display_name"
              placeholder="Acme Corporation"
              {...form.register('display_name')}
              aria-invalid={Boolean(form.formState.errors.display_name)}
            />
            {form.formState.errors.display_name ? (
              <p className="text-xs text-destructive">
                {form.formState.errors.display_name.message}
              </p>
            ) : null}
          </div>

          <div className="space-y-2">
            <Label htmlFor="contact_email">Contact email</Label>
            <Input
              id="contact_email"
              type="email"
              placeholder="ops@acme.example"
              autoComplete="off"
              {...form.register('contact_email')}
              aria-invalid={Boolean(form.formState.errors.contact_email)}
            />
            {form.formState.errors.contact_email ? (
              <p className="text-xs text-destructive">
                {form.formState.errors.contact_email.message}
              </p>
            ) : null}
          </div>

          <div className="flex items-start gap-2 rounded-md border bg-muted/40 p-3">
            <input
              id="fcm_shared"
              type="checkbox"
              className="mt-0.5 h-4 w-4 rounded border-input"
              {...form.register('fcm_shared')}
            />
            <div className="space-y-0.5">
              <Label htmlFor="fcm_shared" className="cursor-pointer">
                Use shared FCM pool
              </Label>
              <p className="text-xs text-muted-foreground">
                Default. Only turn this off for high-volume tenants
                that need a dedicated sender ID (M13b W3 territory).
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button
              type="button"
              variant="ghost"
              onClick={() => setOpen(false)}
              disabled={create.isPending}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={create.isPending}>
              {create.isPending ? 'Creating…' : 'Create company'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
