'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useTranslations } from 'next-intl';
import { useLocale } from 'next-intl';
import { motion } from 'framer-motion';
import { CheckCircle2, LayoutDashboard, LogIn, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';

export default function CompletePage() {
  const t = useTranslations('installer.complete');
  const locale = useLocale();
  const [isCompleting, setIsCompleting] = useState(true);

  useEffect(() => {
    completeSetup();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const completeSetup = async () => {
    const token = sessionStorage.getItem('setup-token') ?? '';
    const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api/v1';

    try {
      await fetch(`${apiUrl}/setup/complete`, {
        method: 'POST',
        headers: { 'x-setup-token': token },
      });
    } catch {
      // Best-effort completion
    } finally {
      sessionStorage.removeItem('setup-token');
      setIsCompleting(false);
    }
  };

  if (isCompleting) {
    return (
      <Card>
        <CardContent className="py-16 flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
          <p className="text-muted-foreground">{t('completing')}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.4 }}
    >
      <Card>
        <CardContent className="py-12 flex flex-col items-center gap-6 text-center">
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: 'spring', delay: 0.1 }}
          >
            <CheckCircle2 className="h-20 w-20 text-green-500" />
          </motion.div>

          <div>
            <h2 className="text-2xl font-bold">{t('title')}</h2>
            <p className="mt-2 text-muted-foreground">{t('description')}</p>
          </div>

          <div className="flex gap-3">
            <Button asChild variant="outline">
              <Link href={`/${locale}/login`}>
                <LogIn className="mr-2 h-4 w-4" />
                {t('toLogin')}
              </Link>
            </Button>
            <Button asChild>
              <Link href={`/${locale}/dashboard`}>
                <LayoutDashboard className="mr-2 h-4 w-4" />
                {t('toDashboard')}
              </Link>
            </Button>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}
