'use client';

import { useState, useTransition } from 'react';

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';

import { Alert, AlertDescription, AlertTitle } from '@kit/ui/alert';
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@kit/ui/alert-dialog';
import { Button } from '@kit/ui/button';
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@kit/ui/form';
import { If } from '@kit/ui/if';
import { Input } from '@kit/ui/input';
import { toast } from '@kit/ui/sonner';

import { createTeamAccountAction } from '../lib/server/admin-server-actions';
import { CreateCompanySchema, CreateCompanySchemaType } from '../lib/server/schema/create-company.schema';
import { Trans } from '@kit/ui/trans';

export function AdminCreateCompanyDialog(props: React.PropsWithChildren) {
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [open, setOpen] = useState(false);

  const form = useForm<CreateCompanySchemaType>({
    resolver: zodResolver(CreateCompanySchema),
    defaultValues: {
      name: '',
    },
    mode: 'onChange',
  });

  const onSubmit = (data: CreateCompanySchemaType) => {
    startTransition(async () => {
      try {
        const error = await createTeamAccountAction(data);

        if (!error) {
          toast.success('Company creates successfully');
          form.reset();

          setOpen(false);
          setError(null);


        } else {
          setError('Something went wrong with company creation');

        }


      } catch (e) {
        setError(e instanceof Error ? e.message : 'Error');
      }
    });
  };

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild>{props.children}</AlertDialogTrigger>

      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Create New Company Account</AlertDialogTitle>

          <AlertDialogDescription>
            Complete the form below to create a new company account.
          </AlertDialogDescription>
        </AlertDialogHeader>

        <Form {...form}>
          <form
            data-test={'admin-create-user-form'}
            className={'flex flex-col space-y-4'}
            onSubmit={form.handleSubmit(onSubmit)}
          >
            <If condition={!!error}>
              <Alert variant={'destructive'}>
                <AlertTitle>Error</AlertTitle>

                <AlertDescription>{error}</AlertDescription>
              </Alert>
            </If>

            <FormField
              name={'name'}
              render={({ field }) => {
                return (
                  <FormItem>
                    <FormLabel>
                      <Trans i18nKey={'teams:teamNameLabel'} />
                    </FormLabel>

                    <FormControl>
                      <Input
                        data-test={'create-team-name-input'}
                        required
                        minLength={2}
                        maxLength={50}
                        placeholder={''}
                        {...field}
                      />
                    </FormControl>

                    <FormDescription>
                      <Trans i18nKey={'teams:teamNameDescription'} />
                    </FormDescription>

                    <FormMessage />
                  </FormItem>
                );
              }}
            />

            <AlertDialogFooter>
              <AlertDialogCancel>Cancel</AlertDialogCancel>

              <Button disabled={pending} type={'submit'}>
                {pending ? 'Creating...' : 'Create Company'}
              </Button>
            </AlertDialogFooter>
          </form>
        </Form>
      </AlertDialogContent>
    </AlertDialog>
  );
}
