'use client';

import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { toast } from 'sonner';

import { Icons } from '@/components/icons';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { SetupEmailCard } from '@/features/foundation/email/components/setup-email-card';
import { cn } from '@/lib/utils';
import {
  useConfiguredBootstrapCsvCommit,
  useConfiguredBootstrapCsvPreview,
  useConfiguredCsvCommit,
  useConfiguredCsvPreview
} from '../api/use-csv-commit';
import { useCompleteBootstrapSetup, useCompleteSetupRun } from '../api/use-setup-run';
import {
  bootstrapSetupRunQueryOptions,
  bootstrapSetupStatusQueryOptions,
  setupRunQueryOptions,
  setupTemplatesQueryOptions
} from '../api/queries';
import type {
  BootstrapRequiredStepDto,
  CsvPreviewError,
  CsvPreviewFileResult,
  CsvPreviewResult,
  ImportReport,
  SetupCheckStatus,
  SetupImportSourceDto,
  SetupImportSourceFileDto,
  SetupRunStepDto,
  SetupStepStatus,
  SetupTemplateMetadataItem
} from '../api/types';

const SAMPLE_ROW_LIMIT = 3;

function getErrorMessage(error: unknown): string {
  if (error instanceof Error) return error.message;
  return 'Unable to complete setup request.';
}

function getPreviewStatus(preview: CsvPreviewResult | null): SetupCheckStatus | null {
  if (!preview) return null;
  if (preview.summary.error > 0 || preview.files.some((file) => file.status === 'FAIL')) return 'FAIL';
  if (preview.summary.warning > 0 || preview.files.some((file) => file.status === 'WARNING')) return 'WARNING';
  return 'PASS';
}

function isStepComplete(step?: SetupRunStepDto): boolean {
  return step?.status === 'passed' || step?.status === 'warning';
}

function statusBadgeVariant(status: SetupStepStatus | SetupCheckStatus | 'found' | 'missing' | 'not_started') {
  if (status === 'failed' || status === 'FAIL' || status === 'missing') return 'destructive';
  if (status === 'warning' || status === 'WARNING' || status === 'stale') return 'secondary';
  if (status === 'passed' || status === 'PASS' || status === 'found') return 'default';
  return 'outline';
}

function StepStatusBadge({ status }: { status: SetupStepStatus | SetupCheckStatus | 'found' | 'missing' | 'not_started' }) {
  return <Badge variant={statusBadgeVariant(status)}>{status}</Badge>;
}

function Metric({ label, value }: { label: string; value: number | string }) {
  return (
    <div className='rounded-md border bg-muted/20 px-3 py-2'>
      <div className='text-xs font-medium uppercase text-muted-foreground'>{label}</div>
      <div className='text-lg font-semibold'>{value}</div>
    </div>
  );
}

function ErrorAlert({ title = 'Request failed', message }: { title?: string; message: string }) {
  return (
    <Alert variant='destructive'>
      <Icons.alertCircle className='h-4 w-4' />
      <AlertTitle>{title}</AlertTitle>
      <AlertDescription>{message}</AlertDescription>
    </Alert>
  );
}

function CsvErrors({ errors }: { errors: CsvPreviewError[] }) {
  if (errors.length === 0) return null;

  return (
    <div className='space-y-2'>
      {errors.slice(0, 8).map((error, index) => (
        <div
          key={`${error.file}-${error.row}-${error.column}-${error.code}-${index}`}
          className='rounded-md border border-destructive/40 bg-destructive/5 p-3 text-sm'
        >
          <div className='font-medium'>{error.code}</div>
          <div>{error.message}</div>
          <div className='text-muted-foreground'>
            {error.file}, row {error.row}, column {error.column}. {error.suggestedFix}
          </div>
        </div>
      ))}
      {errors.length > 8 ? (
        <div className='text-sm text-muted-foreground'>Showing first 8 of {errors.length} issues.</div>
      ) : null}
    </div>
  );
}

function LoadingAlert({ phase }: { phase: string }) {
  return (
    <Alert>
      <Icons.spinner className='h-4 w-4 animate-spin' />
      <AlertTitle>Working</AlertTitle>
      <AlertDescription>{phase}</AlertDescription>
    </Alert>
  );
}

function Stepper({
  steps,
  currentStepKey,
  stepByKey,
  fileByName,
  previewByFileName,
  onSelect
}: {
  steps: BootstrapRequiredStepDto[];
  currentStepKey: string;
  stepByKey: Map<string, SetupRunStepDto>;
  fileByName: Map<string, SetupImportSourceFileDto>;
  previewByFileName: Map<string, CsvPreviewFileResult>;
  onSelect: (stepKey: string) => void;
}) {
  return (
    <Card className='self-start'>
      <CardHeader>
        <CardTitle>System Required</CardTitle>
        <CardDescription>Click a row to inspect the CSV file detail.</CardDescription>
      </CardHeader>
      <CardContent className='space-y-2'>
        {steps.map((step, index) => {
          const persisted = stepByKey.get(step.stepKey);
          const sourceFile = fileByName.get(step.fileName.toLowerCase());
          const previewFile = previewByFileName.get(step.fileName.toLowerCase());
          const selected = currentStepKey === step.stepKey;

          return (
            <button
              key={step.stepKey}
              type='button'
              onClick={() => onSelect(step.stepKey)}
              className={cn(
                'flex min-h-16 w-full items-center gap-3 rounded-md border px-3 py-2 text-left text-sm transition-colors hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
                selected && 'border-primary bg-primary/10'
              )}
            >
              <span className='flex size-8 shrink-0 items-center justify-center rounded-full border bg-background text-xs font-semibold'>
                {index + 1}
              </span>
              <span className='min-w-0 flex-1'>
                <span className='flex items-center gap-2'>
                  {sourceFile ? (
                    <Icons.circleCheck className='size-4 shrink-0 text-primary' />
                  ) : (
                    <Icons.alertCircle className='size-4 shrink-0 text-destructive' />
                  )}
                  <span className='truncate font-medium'>{step.title}</span>
                </span>
                <span className='mt-1 block truncate text-xs text-muted-foreground'>{step.fileName}</span>
              </span>
              <div className='flex shrink-0 flex-col items-end gap-1'>
                <StepStatusBadge status={sourceFile ? 'found' : 'missing'} />
                <StepStatusBadge status={previewFile?.status ?? persisted?.status ?? 'not_started'} />
              </div>
            </button>
          );
        })}
      </CardContent>
    </Card>
  );
}

function SourcePanel({ source }: { source?: SetupImportSourceDto }) {
  if (!source) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Configured Import Folder</CardTitle>
          <CardDescription>Loading setup import source.</CardDescription>
        </CardHeader>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <div className='flex flex-wrap items-start justify-between gap-3'>
          <div>
            <CardTitle>Configured Import Folder</CardTitle>
            <CardDescription>
              Configure CSV source with {source.envKey} in .env, then restart the server.
            </CardDescription>
          </div>
          <Badge variant={source.errors.length > 0 ? 'destructive' : source.warnings.length > 0 ? 'secondary' : 'default'}>
            {source.errors.length > 0 ? 'Not ready' : source.warnings.length > 0 ? 'Warning' : 'Ready'}
          </Badge>
        </div>
      </CardHeader>
      <CardContent className='space-y-4'>
        <div className='grid gap-3 md:grid-cols-2'>
          <div className='rounded-md border p-3'>
            <div className='text-xs font-medium uppercase text-muted-foreground'>Env key</div>
            <div className='mt-1 font-medium'>{source.envKey}</div>
          </div>
          <div className='rounded-md border p-3'>
            <div className='text-xs font-medium uppercase text-muted-foreground'>Configured value</div>
            <div className='mt-1 break-all font-medium'>{source.configuredValue ?? 'Not configured'}</div>
          </div>
          <div className='rounded-md border p-3 md:col-span-2'>
            <div className='text-xs font-medium uppercase text-muted-foreground'>Resolved path</div>
            <div className='mt-1 break-all text-sm'>{source.resolvedPath ?? 'Unavailable'}</div>
          </div>
        </div>

        {source.errors.length > 0 ? (
          <Alert variant='destructive'>
            <Icons.alertCircle className='h-4 w-4' />
            <AlertTitle>Import folder requires configuration</AlertTitle>
            <AlertDescription>
              <div className='space-y-2'>
                {source.errors.map((error) => (
                  <div key={error}>{error}</div>
                ))}
                <code className='block rounded-md bg-background px-3 py-2 text-xs'>
                  {source.envKey}={source.exampleValue}
                </code>
              </div>
            </AlertDescription>
          </Alert>
        ) : null}
      </CardContent>
    </Card>
  );
}

function SelectedFileDetail({
  step,
  sourceFile,
  template,
  previewFile
}: {
  step: BootstrapRequiredStepDto;
  sourceFile?: SetupImportSourceFileDto;
  template?: SetupTemplateMetadataItem;
  previewFile?: CsvPreviewFileResult;
}) {
  const sampleRows = previewFile?.rows.slice(0, SAMPLE_ROW_LIMIT) ?? [];
  const sampleColumns = sampleRows[0] ? Object.keys(sampleRows[0].values) : [];

  return (
    <Card>
      <CardHeader>
        <div className='flex flex-wrap items-start justify-between gap-3'>
          <div>
            <CardTitle>{step.title}</CardTitle>
            <CardDescription>{step.fileName}</CardDescription>
          </div>
          <StepStatusBadge status={sourceFile ? 'found' : 'missing'} />
        </div>
      </CardHeader>
      <CardContent className='space-y-4'>
        {!sourceFile ? (
          <Alert variant='destructive'>
            <Icons.alertCircle className='h-4 w-4' />
            <AlertTitle>File missing</AlertTitle>
            <AlertDescription>Add {step.fileName} to the configured setup import folder.</AlertDescription>
          </Alert>
        ) : (
          <>
            <div className='grid gap-2 sm:grid-cols-3'>
              <Metric label='Bytes' value={sourceFile.bytes.toLocaleString()} />
              <Metric label='Kind' value={sourceFile.kind} />
              <Metric label='Preview' value={previewFile?.status ?? 'not_run'} />
            </div>
            <div className='rounded-md border p-3 text-sm'>
              <div className='text-xs font-medium uppercase text-muted-foreground'>Modified</div>
              <div className='mt-1'>{sourceFile.modifiedAt}</div>
              <div className='mt-3 text-xs font-medium uppercase text-muted-foreground'>Checksum</div>
              <div className='mt-1 break-all'>{sourceFile.checksum}</div>
            </div>
            <div className='rounded-md border p-3'>
              <div className='text-xs font-medium uppercase text-muted-foreground'>Columns</div>
              <div className='mt-2 flex flex-wrap gap-2'>
                {sourceFile.headers.map((header) => (
                  <Badge key={header} variant='outline'>
                    {header}
                  </Badge>
                ))}
              </div>
            </div>
          </>
        )}

        <div className='rounded-md border p-3'>
          <div className='text-xs font-medium uppercase text-muted-foreground'>Required headers</div>
          <div className='mt-2 flex flex-wrap gap-2'>
            {(template?.requiredColumns ?? []).map((column) => (
              <Badge key={column} variant='secondary'>
                {column}
              </Badge>
            ))}
          </div>
        </div>

        {previewFile ? (
          <div className='space-y-3'>
            <div className='grid gap-2 sm:grid-cols-7'>
              <Metric label='Rows' value={previewFile.summary.rows} />
              <Metric label='Valid' value={previewFile.summary.valid} />
              <Metric label='Create' value={previewFile.summary.create} />
              <Metric label='Update' value={previewFile.summary.update} />
              <Metric label='Skip' value={previewFile.summary.skip} />
              <Metric label='Warning' value={previewFile.summary.warning} />
              <Metric label='Error' value={previewFile.summary.error} />
            </div>
            {sampleRows.length > 0 ? (
              <div className='overflow-x-auto rounded-md border'>
                <table className='w-full min-w-[720px] text-sm'>
                  <thead className='bg-muted/50 text-left'>
                    <tr>
                      <th className='px-3 py-2 font-medium'>Row</th>
                      <th className='px-3 py-2 font-medium'>Action</th>
                      {sampleColumns.map((column) => (
                        <th key={column} className='px-3 py-2 font-medium'>
                          {column}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody>
                    {sampleRows.map((row) => (
                      <tr key={row.row} className='border-t'>
                        <td className='px-3 py-2'>{row.row}</td>
                        <td className='px-3 py-2'>{row.action}</td>
                        {sampleColumns.map((column) => (
                          <td key={`${row.row}-${column}`} className='max-w-[220px] truncate px-3 py-2'>
                            {row.values[column] || '-'}
                          </td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : null}
            <CsvErrors errors={[...previewFile.errors, ...previewFile.warnings]} />
          </div>
        ) : (
          <div className='rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground'>
            Click Execute Import Seed Data to preview and import the configured CSV files.
          </div>
        )}
      </CardContent>
    </Card>
  );
}

function ImportReportPanel({ report }: { report: ImportReport | null }) {
  if (!report) return null;

  return (
    <Alert variant={report.status === 'FAIL' ? 'destructive' : 'default'}>
      {report.status === 'FAIL' ? <Icons.alertCircle className='h-4 w-4' /> : <Icons.circleCheck className='h-4 w-4' />}
      <AlertTitle>{report.status === 'FAIL' ? 'Import failed and was rolled back' : 'Import completed successfully'}</AlertTitle>
      <AlertDescription>
        Imported {report.summary.imported}, updated {report.summary.updated}, skipped {report.summary.skipped}, warnings{' '}
        {report.summary.warnings}, errors {report.summary.errors}.
      </AlertDescription>
    </Alert>
  );
}

interface SetupWizardProps {
  mode?: 'admin' | 'public';
  tokenRequired?: boolean;
}

export function SetupWizard({ mode = 'admin', tokenRequired = false }: SetupWizardProps) {
  const [currentStepKey, setCurrentStepKey] = useState('');
  const [preview, setPreview] = useState<CsvPreviewResult | null>(null);
  const [importReport, setImportReport] = useState<ImportReport | null>(null);
  const [warningAcknowledged, setWarningAcknowledged] = useState(false);
  const [bootstrapToken, setBootstrapToken] = useState('');
  const [workingMessage, setWorkingMessage] = useState<string | null>(null);

  const bootstrapTokenReady = mode !== 'public' || !tokenRequired || bootstrapToken.trim().length > 0;
  const bootstrapStatusQuery = useQuery(bootstrapSetupStatusQueryOptions());
  const templatesQuery = useQuery(setupTemplatesQueryOptions('production'));
  const adminSetupRunQuery = useQuery({ ...setupRunQueryOptions(), enabled: mode === 'admin' });
  const publicSetupRunQuery = useQuery({
    ...bootstrapSetupRunQueryOptions(bootstrapToken.trim() || undefined),
    enabled: mode === 'public' && bootstrapTokenReady
  });
  const setupRunQuery = mode === 'public' ? publicSetupRunQuery : adminSetupRunQuery;

  const adminPreviewMutation = useConfiguredCsvPreview();
  const adminCommitMutation = useConfiguredCsvCommit();
  const bootstrapPreviewMutation = useConfiguredBootstrapCsvPreview();
  const bootstrapCommitMutation = useConfiguredBootstrapCsvCommit();
  const completeBootstrapMutation = useCompleteBootstrapSetup();
  const completeAdminMutation = useCompleteSetupRun();

  const previewMutation = mode === 'public' ? bootstrapPreviewMutation : adminPreviewMutation;
  const commitMutation = mode === 'public' ? bootstrapCommitMutation : adminCommitMutation;
  const completeMutation = mode === 'public' ? completeBootstrapMutation : completeAdminMutation;

  const steps = bootstrapStatusQuery.data?.requiredSteps ?? [];
  const importSource = bootstrapStatusQuery.data?.importSource;
  const sourceReady = Boolean(importSource && importSource.errors.length === 0);
  const previewStatus = getPreviewStatus(preview);
  const isWorking = previewMutation.isPending || commitMutation.isPending || completeMutation.isPending || Boolean(workingMessage);

  const stepByKey = useMemo(() => {
    const entries = setupRunQuery.data?.steps.map((step) => [step.stepKey, step] as const) ?? [];
    return new Map(entries);
  }, [setupRunQuery.data?.steps]);

  const fileByName = useMemo(() => {
    const entries = importSource?.files.map((file) => [file.fileName.toLowerCase(), file] as const) ?? [];
    return new Map(entries);
  }, [importSource?.files]);

  const previewByFileName = useMemo(() => {
    const entries = preview?.files.map((file) => [file.fileName.toLowerCase(), file] as const) ?? [];
    return new Map(entries);
  }, [preview?.files]);

  const templateByFile = useMemo(() => {
    const entries = templatesQuery.data?.templates.map((template) => [template.file, template] as const) ?? [];
    return new Map(entries);
  }, [templatesQuery.data?.templates]);

  const currentStep = steps.find((step) => step.stepKey === currentStepKey) ?? steps[0] ?? null;
  const selectedSourceFile = currentStep ? fileByName.get(currentStep.fileName.toLowerCase()) : undefined;
  const selectedPreviewFile = currentStep ? previewByFileName.get(currentStep.fileName.toLowerCase()) : undefined;
  const selectedTemplate = currentStep ? templateByFile.get(currentStep.fileName) : undefined;
  const persistedComplete = steps.length > 0 && steps.every((step) => isStepComplete(stepByKey.get(step.stepKey)));
  const importSucceeded = importReport?.status === 'PASS' || importReport?.status === 'WARNING';
  const allRequiredComplete = persistedComplete || importSucceeded;
  const submitDisabled = !bootstrapTokenReady || !sourceReady || isWorking;

  async function runPreviewOnly() {
    const result =
      mode === 'public'
        ? await bootstrapPreviewMutation.mutateAsync({ bootstrapToken: bootstrapToken.trim() || undefined })
        : await adminPreviewMutation.mutateAsync();

    setPreview(result);
    setImportReport(null);
    await Promise.all([setupRunQuery.refetch(), bootstrapStatusQuery.refetch()]);
    return result;
  }

  async function executeImportSeedData() {
    setWorkingMessage('Previewing setup CSV files from the configured folder...');
    setImportReport(null);

    try {
      const previewResult = await runPreviewOnly();
      const status = getPreviewStatus(previewResult);

      if (status === 'FAIL') {
        toast.error('Import blocked because preview has errors. No data was imported.');
        return;
      }

      if (status === 'WARNING' && !warningAcknowledged) {
        toast.error('Acknowledge preview warnings before importing seed data.');
        return;
      }

      setWorkingMessage('Importing seed data in a transaction. Failed imports roll back automatically...');

      const result =
        mode === 'public'
          ? await bootstrapCommitMutation.mutateAsync({
              previewHash: previewResult.previewHash,
              bootstrapToken: bootstrapToken.trim() || undefined
            })
          : await adminCommitMutation.mutateAsync({ previewHash: previewResult.previewHash });

      setImportReport(result);
      await Promise.all([setupRunQuery.refetch(), bootstrapStatusQuery.refetch()]);

      if (result.status === 'FAIL') {
        toast.error('Import failed. Database changes were rolled back.');
        return;
      }

      toast.success('Import seed data completed successfully.');
    } catch (error) {
      toast.error(`${getErrorMessage(error)} Database changes were rolled back.`);
    } finally {
      setWorkingMessage(null);
    }
  }

  async function completeSetup() {
    if (mode === 'public') {
      await completeBootstrapMutation.mutateAsync({
        bootstrapToken: bootstrapToken.trim() || undefined,
        report: {
          source: 'configured-directory-bootstrap',
          requiredStepKeys: steps.map((step) => step.stepKey)
        }
      });
      window.location.assign('/auth/sign-in');
      return;
    }

    await completeAdminMutation.mutateAsync({
      source: 'configured-directory-admin',
      requiredStepKeys: steps.map((step) => step.stepKey)
    });
  }

  if (bootstrapStatusQuery.isLoading || templatesQuery.isLoading || setupRunQuery.isLoading) {
    return (
      <div className='rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground'>
        Loading setup import preview...
      </div>
    );
  }

  if (!currentStep) {
    return (
      <Alert>
        <Icons.info className='h-4 w-4' />
        <AlertTitle>No required setup steps</AlertTitle>
        <AlertDescription>The setup API did not return any required bootstrap steps.</AlertDescription>
      </Alert>
    );
  }

  return (
    <div className='space-y-6'>
      <div className='flex flex-wrap items-start justify-between gap-3 rounded-lg border bg-background p-4'>
        <div>
          <div className='text-lg font-semibold'>Setup Import Form</div>
          <div className='text-sm text-muted-foreground'>
            Execute import seed data from the configured folder. Failed imports roll back in the commit transaction.
          </div>
        </div>
        <div className='flex flex-wrap gap-2'>
          <Button
            type='button'
            variant='outline'
            onClick={runPreviewOnly}
            disabled={!bootstrapTokenReady || !sourceReady || isWorking}
          >
            {previewMutation.isPending ? <Icons.spinner className='mr-2 h-4 w-4 animate-spin' /> : <Icons.page className='mr-2 h-4 w-4' />}
            Refresh Preview
          </Button>
          <Button type='button' onClick={executeImportSeedData} disabled={submitDisabled}>
            {isWorking ? <Icons.spinner className='mr-2 h-4 w-4 animate-spin' /> : <Icons.check className='mr-2 h-4 w-4' />}
            Execute Import Seed Data
          </Button>
        </div>
      </div>

      {workingMessage ? <LoadingAlert phase={workingMessage} /> : null}
      {importReport ? <ImportReportPanel report={importReport} /> : null}

      {previewStatus === 'WARNING' ? (
        <div className='flex items-center gap-2 rounded-md border p-3 text-sm'>
          <Checkbox
            id='setup-preview-warning-acknowledgement'
            checked={warningAcknowledged}
            onCheckedChange={(checked) => setWarningAcknowledged(checked === true)}
          />
          <label htmlFor='setup-preview-warning-acknowledgement'>Acknowledge warnings and allow import.</label>
        </div>
      ) : null}

      {mode === 'public' && tokenRequired ? (
        <Card>
          <CardHeader>
            <CardTitle>Bootstrap Token</CardTitle>
            <CardDescription>Enter the setup token before running protected bootstrap steps.</CardDescription>
          </CardHeader>
          <CardContent>
            <Input
              type='password'
              value={bootstrapToken}
              onChange={(event) => setBootstrapToken(event.target.value)}
              placeholder='Bootstrap setup token'
              aria-label='Bootstrap setup token'
            />
          </CardContent>
        </Card>
      ) : null}

      <div className='grid gap-6 lg:grid-cols-[360px_1fr]'>
        <Stepper
          steps={steps}
          currentStepKey={currentStep.stepKey}
          stepByKey={stepByKey}
          fileByName={fileByName}
          previewByFileName={previewByFileName}
          onSelect={setCurrentStepKey}
        />

<div className='space-y-6'>
<SourcePanel source={importSource} />
<SelectedFileDetail
            step={currentStep}
            sourceFile={selectedSourceFile}
            template={selectedTemplate}
            previewFile={selectedPreviewFile}
          />
<SetupEmailCard />

<Card>
            <CardHeader>
              <CardTitle>Final Verification</CardTitle>
              <CardDescription>Setup can complete after system-required import steps pass.</CardDescription>
            </CardHeader>
            <CardContent className='space-y-4'>
              <div className='grid gap-2 sm:grid-cols-3'>
                <Metric
                  label='Required'
                  value={`${steps.filter((step) => isStepComplete(stepByKey.get(step.stepKey))).length}/${steps.length}`}
                />
                <Metric label='Status' value={allRequiredComplete ? 'Ready' : 'Incomplete'} />
                <Metric label='Result' value={setupRunQuery.data?.run?.status ?? 'not_started'} />
              </div>
              <Button type='button' onClick={completeSetup} disabled={!allRequiredComplete || completeMutation.isPending}>
                {completeMutation.isPending ? (
                  <Icons.spinner className='mr-2 h-4 w-4 animate-spin' />
                ) : (
                  <Icons.checks className='mr-2 h-4 w-4' />
                )}
                Mark setup completed
              </Button>
              {completeMutation.isError ? <ErrorAlert message={getErrorMessage(completeMutation.error)} /> : null}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
