'use client';

import Link from 'next/link';
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
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 { emailConfigurationsQueryOptions } from '../api/queries';

export function SetupEmailCard() {
  const query = useQuery(emailConfigurationsQueryOptions());

  const summary = useMemo(() => {
    const configurations = query.data ?? [];
    const defaultConfiguration = configurations.find((item) => item.isDefault) ?? null;
    const passingCount = configurations.filter((item) => item.lastTestStatus === 'passed').length;

    return {
      total: configurations.length,
      defaultName: defaultConfiguration?.name ?? 'Not configured',
      passingCount,
    };
  }, [query.data]);

  return (
    <Card>
      <CardHeader>
        <div className='flex flex-wrap items-start justify-between gap-3'>
          <div>
            <CardTitle>Email Delivery</CardTitle>
            <CardDescription>
              Optional setup step for SMTP readiness. This does not block setup unless your chosen profile requires it.
            </CardDescription>
          </div>
          <Badge variant='outline'>Optional</Badge>
        </div>
      </CardHeader>
      <CardContent className='space-y-4'>
        {query.isLoading ? (
          <div className='flex items-center gap-2 text-sm text-muted-foreground'>
            <Icons.spinner className='h-4 w-4 animate-spin' />
            Loading email configuration status...
          </div>
        ) : null}

        {query.isError ? (
          <Alert variant='destructive'>
            <Icons.alertCircle className='h-4 w-4' />
            <AlertTitle>Unable to load email status</AlertTitle>
            <AlertDescription>
              {query.error instanceof Error ? query.error.message : 'Unknown email configuration error.'}
            </AlertDescription>
          </Alert>
        ) : null}

        {!query.isLoading && !query.isError ? (
          <>
            <div className='grid gap-2 sm:grid-cols-3'>
              <div className='rounded-md border p-3'>
                <div className='text-xs font-medium uppercase text-muted-foreground'>Profiles</div>
                <div className='text-lg font-semibold'>{summary.total}</div>
              </div>
              <div className='rounded-md border p-3'>
                <div className='text-xs font-medium uppercase text-muted-foreground'>Ready</div>
                <div className='text-lg font-semibold'>{summary.passingCount}</div>
              </div>
              <div className='rounded-md border p-3'>
                <div className='text-xs font-medium uppercase text-muted-foreground'>Default</div>
                <div className='truncate text-sm font-semibold'>{summary.defaultName}</div>
              </div>
            </div>

            <div className='rounded-md border border-dashed p-4 text-sm text-muted-foreground'>
              Configure SMTP now if you want setup verification to include live email readiness against the active organization.
            </div>
          </>
        ) : null}

        <Button asChild type='button' variant='outline'>
          <Link href='/dashboard/administration/email'>Open email configuration</Link>
        </Button>
      </CardContent>
    </Card>
  );
}
