'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useLocale } from 'next-intl';
import { motion } from 'framer-motion';
import { CheckCircle2, XCircle, Loader2, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

type ServiceStatus = 'checking' | 'online' | 'offline';

interface StatusRowProps {
  label: string;
  status: ServiceStatus;
  onlineLabel: string;
  offlineLabel: string;
  checkingLabel: string;
}

function StatusRow({ label, status, onlineLabel, offlineLabel, checkingLabel }: StatusRowProps) {
  return (
    <div className="flex items-center justify-between py-3 border-b last:border-0">
      <span className="font-medium">{label}</span>
      <div className="flex items-center gap-2">
        {status === 'checking' && (
          <>
            <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
            <span className="text-sm text-muted-foreground">{checkingLabel}</span>
          </>
        )}
        {status === 'online' && (
          <>
            <CheckCircle2 className="h-4 w-4 text-green-500" />
            <span className="text-sm text-green-600 font-medium">{onlineLabel}</span>
          </>
        )}
        {status === 'offline' && (
          <>
            <XCircle className="h-4 w-4 text-destructive" />
            <span className="text-sm text-destructive font-medium">{offlineLabel}</span>
          </>
        )}
      </div>
    </div>
  );
}

export default function SetupPage() {
  const t = useTranslations('installer.systemCheck');
  const router = useRouter();
  const locale = useLocale();
  const searchParams = useSearchParams();

  const [apiStatus, setApiStatus] = useState<ServiceStatus>('checking');
  const [dbStatus, setDbStatus] = useState<ServiceStatus>('checking');
  const [keycloakStatus, setKeycloakStatus] = useState<ServiceStatus>('checking');
  const [setupComplete, setSetupComplete] = useState(false);
  const [allOnline, setAllOnline] = useState(false);

  useEffect(() => {
    // Store setup token from URL in sessionStorage
    const token = searchParams.get('token');
    if (token) {
      sessionStorage.setItem('setup-token', token);
    }

    checkServices();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (apiStatus === 'online' && dbStatus === 'online' && keycloakStatus === 'online') {
      setAllOnline(true);
    }
  }, [apiStatus, dbStatus, keycloakStatus]);

  const checkServices = async () => {
    const apiUrl = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:3001/api/v1';

    // Check API
    try {
      const res = await fetch(`${apiUrl}/health/liveness`);
      if (res.ok) {
        setApiStatus('online');
        setDbStatus('online'); // If API is up, DB is connected
      } else {
        setApiStatus('offline');
        setDbStatus('offline');
      }
    } catch {
      setApiStatus('offline');
      setDbStatus('offline');
    }

    // Check Setup Status
    try {
      const res = await fetch(`${apiUrl}/setup/status`);
      if (res.ok) {
        const data = await res.json();
        // Handle response envelope
        const status = data.data ?? data;
        if (status.completed) {
          setSetupComplete(true);
          setTimeout(() => router.push(`/${locale}/dashboard`), 3000);
          return;
        }
        setKeycloakStatus('online');
      } else {
        setKeycloakStatus('offline');
      }
    } catch {
      setKeycloakStatus('offline');
    }
  };

  if (setupComplete) {
    return (
      <Card>
        <CardContent className="py-12 text-center">
          <CheckCircle2 className="mx-auto h-12 w-12 text-green-500 mb-4" />
          <p className="font-medium">{t('alreadyComplete')}</p>
          <p className="text-sm text-muted-foreground mt-1">{t('redirecting')}</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <Card>
        <CardHeader>
          <CardTitle>{t('title')}</CardTitle>
          <CardDescription>{t('description')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <StatusRow
              label={t('api')}
              status={apiStatus}
              onlineLabel={t('online')}
              offlineLabel={t('offline')}
              checkingLabel={t('checking')}
            />
            <StatusRow
              label={t('database')}
              status={dbStatus}
              onlineLabel={t('online')}
              offlineLabel={t('offline')}
              checkingLabel={t('checking')}
            />
            <StatusRow
              label={t('keycloak')}
              status={keycloakStatus}
              onlineLabel={t('online')}
              offlineLabel={t('offline')}
              checkingLabel={t('checking')}
            />
          </div>

          <div className="flex justify-end pt-4">
            <Button onClick={() => router.push(`/${locale}/setup/admin`)} disabled={!allOnline}>
              {t('continue')}
              <ArrowRight className="ml-2 h-4 w-4" />
            </Button>
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}
