import { cn } from '@documenso/ui/lib/utils';
import { Alert, AlertDescription } from '@documenso/ui/primitives/alert';
import { Button } from '@documenso/ui/primitives/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@documenso/ui/primitives/card';
import { Checkbox } from '@documenso/ui/primitives/checkbox';
import { SigningOrderConfirmation } from '@documenso/ui/primitives/document-flow/signing-order-confirmation';
import { Form, FormControl, FormField, FormItem, FormLabel } from '@documenso/ui/primitives/form/form';
import { FormErrorMessage } from '@documenso/ui/primitives/form/form-error-message';

import { Tooltip, TooltipContent, TooltipTrigger } from '@documenso/ui/primitives/tooltip';

import { Trans } from '@lingui/react/macro';
import { DocumentSigningOrder } from '@prisma/client';

import { HelpCircleIcon, PlusIcon, SparklesIcon } from 'lucide-react';

import { AiFeaturesEnableDialog } from '~/components/dialogs/ai-features-enable-dialog';
import { AiRecipientDetectionDialog } from '~/components/dialogs/ai-recipient-detection-dialog';

import { EnvelopeEditorRecipientList } from './envelope-editor-recipient-list';
import { useEnvelopeEditorRecipients } from './use-envelope-editor-recipients';

export const EnvelopeEditorRecipientForm = () => {
  const state = useEnvelopeEditorRecipients();
  const {
    envelope,
    editorConfig,
    isEmbedded,
    organisation,
    team,
    remaining,
    form,
    isSubmitting,
    errors,
    signers,
    hasCurrentEditorInfo,
    isUserAlreadyARecipient,
    onAddSelfSigner,
    onAddSigner,
    onDetectRecipientsClick,
    isOverRecipientLimit,
    recipientCountLimit,
    showAdvancedSettings,
    setShowAdvancedSettings,
    hasAssistantRole,
    setShowSigningOrderConfirmation,
    hasDocumentBeenSent,
    isSigningOrderSequential,
    showSigningOrderConfirmation,
    handleSigningOrderDisable,
    isAiDialogOpen,
    onAiDialogOpenChange,
    onAiDetectionComplete,
    isAiEnableDialogOpen,
    setIsAiEnableDialogOpen,
    onAiFeaturesEnabled,
  } = state;

  return (
    <Card backdropBlur={false} className="border">
      <CardHeader className="flex flex-col gap-3 space-y-0 p-4 sm:p-6 xl:flex-row xl:items-start xl:justify-between">
        <div>
          <CardTitle>
            <Trans>Recipients</Trans>
          </CardTitle>
          <CardDescription className="mt-1.5">
            <Trans>Add recipients to your document</Trans>
          </CardDescription>
        </div>

        <div className="flex min-w-0 flex-wrap items-center gap-2">
          {editorConfig.recipients?.allowAIDetection && (
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="outline"
                  type="button"
                  size="sm"
                  disabled={isSubmitting}
                  onClick={onDetectRecipientsClick}
                >
                  <SparklesIcon className="h-4 w-4" />
                </Button>
              </TooltipTrigger>

              <TooltipContent>
                {team.preferences.aiFeaturesEnabled ? (
                  <Trans>Detect recipients with AI</Trans>
                ) : (
                  <Trans>Enable AI detection</Trans>
                )}
              </TooltipContent>
            </Tooltip>
          )}

          {(!isEmbedded || hasCurrentEditorInfo) && (
            <Button
              variant="outline"
              className="flex flex-row items-center"
              size="sm"
              disabled={isSubmitting || isUserAlreadyARecipient}
              onClick={() => onAddSelfSigner()}
            >
              <Trans>Add Myself</Trans>
            </Button>
          )}

          <Button
            variant="outline"
            type="button"
            className="flex-1"
            size="sm"
            disabled={isSubmitting || signers.length >= remaining.recipients}
            onClick={() => onAddSigner()}
          >
            <PlusIcon className="mr-1 -ml-1 h-5 w-5" />
            <Trans>Add Signer</Trans>
          </Button>
        </div>
      </CardHeader>

      <CardContent className="p-4 pt-0 sm:p-6 sm:pt-0">
        {isOverRecipientLimit && (
          <Alert variant="destructive" className="mb-4">
            <AlertDescription>
              <Trans>
                This envelope cannot have more than {recipientCountLimit} recipients. Please contact support if you need
                more.
              </Trans>
            </AlertDescription>
          </Alert>
        )}

        <Form {...form}>
          <div
            className={cn('-mt-2 mb-2 space-y-4 rounded-md bg-accent/50 p-4', {
              hidden:
                !editorConfig.recipients?.allowConfigureSigningOrder && !organisation.organisationClaim.flags.cfr21,
            })}
          >
            {organisation.organisationClaim.flags.cfr21 && (
              <div className="flex flex-row items-center">
                <Checkbox
                  id="showAdvancedRecipientSettings"
                  checked={showAdvancedSettings}
                  onCheckedChange={(value) => setShowAdvancedSettings(Boolean(value))}
                />

                <label
                  className="ml-2 text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                  htmlFor="showAdvancedRecipientSettings"
                >
                  <Trans>Show advanced settings</Trans>
                </label>
              </div>
            )}

            {editorConfig.recipients?.allowConfigureSigningOrder && (
              <FormField
                control={form.control}
                name="signingOrder"
                render={({ field }) => (
                  <FormItem className="flex flex-row items-center space-x-2 space-y-0">
                    <FormControl>
                      <Checkbox
                        {...field}
                        id="signingOrder"
                        checked={field.value === DocumentSigningOrder.SEQUENTIAL}
                        onCheckedChange={(checked) => {
                          if (!checked && hasAssistantRole) {
                            setShowSigningOrderConfirmation(true);
                            return;
                          }

                          field.onChange(checked ? DocumentSigningOrder.SEQUENTIAL : DocumentSigningOrder.PARALLEL);

                          // If sequential signing is turned off, disable dictate next signer
                          if (!checked) {
                            form.setValue('allowDictateNextSigner', false, {
                              shouldValidate: true,
                              shouldDirty: true,
                            });
                          }
                        }}
                        disabled={isSubmitting || hasDocumentBeenSent}
                      />
                    </FormControl>

                    <div className="flex items-center text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                      <FormLabel
                        htmlFor="signingOrder"
                        className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        <Trans>Enable signing order</Trans>
                      </FormLabel>

                      <Tooltip>
                        <TooltipTrigger asChild>
                          <span className="ml-1 cursor-help text-muted-foreground">
                            <HelpCircleIcon className="h-3.5 w-3.5" />
                          </span>
                        </TooltipTrigger>
                        <TooltipContent className="max-w-80 p-4">
                          <p>
                            <Trans>Add 2 or more signers to enable signing order.</Trans>
                          </p>
                        </TooltipContent>
                      </Tooltip>
                    </div>
                  </FormItem>
                )}
              />
            )}

            {isSigningOrderSequential && (
              <FormField
                control={form.control}
                name="allowDictateNextSigner"
                render={({ field: { value, ...field } }) => (
                  <FormItem className="flex flex-row items-center space-x-2 space-y-0">
                    <FormControl>
                      <Checkbox
                        {...field}
                        id="allowDictateNextSigner"
                        checked={value}
                        onCheckedChange={(checked) => {
                          field.onChange(checked);
                        }}
                        disabled={isSubmitting || hasDocumentBeenSent || !isSigningOrderSequential}
                      />
                    </FormControl>

                    <div className="flex items-center text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
                      <FormLabel
                        htmlFor="allowDictateNextSigner"
                        className="text-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                      >
                        <Trans>Allow signers to dictate next signer</Trans>
                      </FormLabel>

                      <Tooltip>
                        <TooltipTrigger asChild>
                          <span className="ml-1 cursor-help text-muted-foreground">
                            <HelpCircleIcon className="h-3.5 w-3.5" />
                          </span>
                        </TooltipTrigger>
                        <TooltipContent className="max-w-80 p-4">
                          <p>
                            <Trans>
                              When enabled, signers can choose who should sign next in the sequence instead of following
                              the predefined order.
                            </Trans>
                          </p>
                        </TooltipContent>
                      </Tooltip>
                    </div>
                  </FormItem>
                )}
              />
            )}
          </div>

          <EnvelopeEditorRecipientList state={state} />

          <FormErrorMessage
            className="mt-2"
            // Dirty hack to handle errors when .root is populated for an array type
            error={'signers__root' in errors && errors['signers__root']}
          />
        </Form>

        <SigningOrderConfirmation
          open={showSigningOrderConfirmation}
          onOpenChange={setShowSigningOrderConfirmation}
          onConfirm={handleSigningOrderDisable}
        />

        {editorConfig.recipients?.allowAIDetection && (
          <AiRecipientDetectionDialog
            open={isAiDialogOpen}
            onOpenChange={onAiDialogOpenChange}
            onComplete={onAiDetectionComplete}
            envelopeId={envelope.id}
            teamId={envelope.teamId}
          />
        )}

        <AiFeaturesEnableDialog
          open={isAiEnableDialogOpen}
          onOpenChange={setIsAiEnableDialogOpen}
          onEnabled={onAiFeaturesEnabled}
        />
      </CardContent>
    </Card>
  );
};
