'use client';

import { useTranslations } from 'next-intl';
import Link from 'next/link';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import {
  ArrowLeft,
  Building2,
  MessageSquare,
  CheckSquare,
  Headphones,
  Cloud,
  FileText,
  ClipboardCheck,
  RefreshCw,
  Settings,
  type LucideIcon,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { IntegrationStatusBadge, SyncStatus, ConnectionTestButton } from '@/components/integrations';
import { useIntegrationStatus, useTriggerSync } from '@/hooks/integrations';
import type { IntegrationType } from '@/types/integrations';

// Integration-specific content imports
import { PlentyOneContent } from './plentyone-content';
import { ZulipContent } from './zulip-content';
import { TodoistContent } from './todoist-content';
import { FreeScoutContent } from './freescout-content';
import { NextcloudContent } from './nextcloud-content';
import { EcoDmsContent } from './ecodms-content';
import { GembaDocsContent } from './gembadocs-content';

interface IntegrationDetailContentProps {
  locale: string;
  integrationType: IntegrationType;
}

/** Integration metadata */
const integrationMeta: Record<
  IntegrationType,
  { icon: LucideIcon; nameKey: string; descKey: string }
> = {
  plentyone: { icon: Building2, nameKey: 'plentyOne', descKey: 'plentyOneDesc' },
  zulip: { icon: MessageSquare, nameKey: 'zulip', descKey: 'zulipDesc' },
  todoist: { icon: CheckSquare, nameKey: 'todoist', descKey: 'todoistDesc' },
  freescout: { icon: Headphones, nameKey: 'freeScout', descKey: 'freeScoutDesc' },
  nextcloud: { icon: Cloud, nameKey: 'nextcloud', descKey: 'nextcloudDesc' },
  ecodms: { icon: FileText, nameKey: 'ecoDms', descKey: 'ecoDmsDesc' },
  gembadocs: { icon: ClipboardCheck, nameKey: 'gembaDocs', descKey: 'gembaDocsDesc' },
};

/** Integration-specific content components */
const integrationContentMap: Record<IntegrationType, React.ComponentType<{ locale: string }>> = {
  plentyone: PlentyOneContent,
  zulip: ZulipContent,
  todoist: TodoistContent,
  freescout: FreeScoutContent,
  nextcloud: NextcloudContent,
  ecodms: EcoDmsContent,
  gembadocs: GembaDocsContent,
};

/**
 * Integration detail page content
 */
export function IntegrationDetailContent({
  locale,
  integrationType,
}: IntegrationDetailContentProps) {
  const t = useTranslations('integrations');
  const { data: config, isLoading } = useIntegrationStatus(integrationType);
  const triggerSync = useTriggerSync();
  const dateLocale = locale === 'de' ? de : enUS;

  const meta = integrationMeta[integrationType];
  const ContentComponent = integrationContentMap[integrationType];

  const handleSync = () => {
    triggerSync.mutate(integrationType);
  };

  // Integration type not supported
  if (!meta) {
    return (
      <div className="container mx-auto space-y-6 py-6">
        <Button variant="ghost" size="sm" asChild>
          <Link href={`/${locale}/integrations`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            {t('overview')}
          </Link>
        </Button>
        <p className="text-muted-foreground">{t('notFound')}</p>
      </div>
    );
  }

  const Icon = meta.icon;

  if (isLoading) {
    return (
      <div className="container mx-auto space-y-6 py-6">
        <Skeleton className="h-8 w-48" />
        <Card>
          <CardHeader>
            <Skeleton className="h-12 w-12 rounded-lg" />
            <Skeleton className="mt-2 h-6 w-32" />
            <Skeleton className="mt-1 h-4 w-48" />
          </CardHeader>
          <CardContent>
            <Skeleton className="h-32 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  // Use API data or fallback to disconnected state
  const displayConfig = config ?? {
    id: integrationType,
    type: integrationType,
    name: t(meta.nameKey as never),
    enabled: false,
    status: 'disconnected' as const,
    lastSync: undefined,
    lastError: undefined,
    syncInterval: 15,
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  return (
    <div className="container mx-auto space-y-6 py-6">
      {/* Back link */}
      <Button variant="ghost" size="sm" asChild>
        <Link href={`/${locale}/integrations`}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          {t('overview')}
        </Link>
      </Button>

      {/* Header Card */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
      >
        <Card>
          <CardHeader>
            <div className="flex items-start justify-between">
              <div className="flex items-center gap-4">
                <div
                  className={cn(
                    'flex h-12 w-12 items-center justify-center rounded-lg',
                    displayConfig.enabled ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'
                  )}
                >
                  <Icon className="h-6 w-6" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <CardTitle className="text-xl">{t(meta.nameKey as never)}</CardTitle>
                    <IntegrationStatusBadge status={displayConfig.status} />
                  </div>
                  <CardDescription>{t(meta.descKey as never)}</CardDescription>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <ConnectionTestButton integrationType={integrationType} />
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleSync}
                  disabled={triggerSync.isPending || displayConfig.status !== 'connected'}
                >
                  <RefreshCw
                    className={cn('mr-2 h-4 w-4', triggerSync.isPending && 'animate-spin')}
                  />
                  {t('syncNow')}
                </Button>
              </div>
            </div>
          </CardHeader>

          <CardContent>
            <SyncStatus
              lastSync={displayConfig.lastSync}
              locale={locale}
              error={displayConfig.lastError}
            />
          </CardContent>
        </Card>
      </motion.div>

      {/* Tabs */}
      <Tabs defaultValue="data" className="space-y-4">
        <TabsList>
          <TabsTrigger value="data">{t('data')}</TabsTrigger>
          <TabsTrigger value="settings">
            <Settings className="mr-2 h-4 w-4" />
            {t('settingsTab')}
          </TabsTrigger>
          <TabsTrigger value="logs">{t('logs')}</TabsTrigger>
        </TabsList>

        <TabsContent value="data" className="space-y-4">
          {ContentComponent && <ContentComponent locale={locale} />}
        </TabsContent>

        <TabsContent value="settings">
          <Card>
            <CardHeader>
              <CardTitle>{t('credentials')}</CardTitle>
              <CardDescription>
                {t('configureCredentials')}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <p className="text-sm text-muted-foreground">
                {t('settingsManagedViaAdmin')}
              </p>
              <Button variant="outline" asChild>
                <Link href={`/${locale}/admin/integrations/${integrationType}`}>
                  <Settings className="mr-2 h-4 w-4" />
                  {t('configure')}
                </Link>
              </Button>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="logs">
          <Card>
            <CardHeader>
              <CardTitle>{t('syncLogs')}</CardTitle>
              <CardDescription>
                {t('recentSyncActivity')}
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2 text-sm">
                <div className="flex items-center justify-between border-b py-2">
                  <span className="text-muted-foreground">{t('syncSuccessful')}</span>
                  <span>
                    {displayConfig.lastSync
                      ? formatDistanceToNow(displayConfig.lastSync, { addSuffix: true, locale: dateLocale })
                      : '-'}
                  </span>
                </div>
                {displayConfig.lastError && (
                  <div className="rounded-lg bg-destructive/10 p-3 text-destructive">
                    <p className="font-medium">{t('lastError')}</p>
                    <p>{displayConfig.lastError}</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
