'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import {
  Shield,
  Building2,
  MessageSquare,
  CheckSquare,
  Headphones,
  Cloud,
  FileText,
  ClipboardCheck,
  Settings,
  Eye,
  EyeOff,
  Loader2,
  Plug,
  CheckCircle2,
  AlertCircle,
  LayoutGrid,
  type LucideIcon,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { IntegrationStatusBadge, IntegrationCard } from '@/components/integrations';
import { useAllIntegrationStatuses } from '@/hooks/integrations';
import {
  useCredentials,
  useCredentialDetail,
  useCreateCredential,
  useUpdateCredential,
  useTestCredentialConnection,
} from '@/hooks/integrations/use-credentials';
import { useUpdateSetting } from '@/hooks/use-system-settings';
import { useToast } from '@/hooks/use-toast';
import type { IntegrationType } from '@/types/integrations';

interface AdminIntegrationsContentProps {
  locale: string;
}

// ============================================================
// Static configuration
// ============================================================

/** Display metadata per integration */
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' },
};

/** Credential field definitions per integration.
 *  Keys must match what the backend validates (credentials.service.ts). */
const credentialFields: Record<
  IntegrationType,
  Array<{ key: string; label: string; type: 'text' | 'password' | 'url'; placeholder?: string }>
> = {
  plentyone: [
    { key: 'apiUrl', label: 'API URL', type: 'url', placeholder: 'https://your-shop.plentymarkets-cloud01.com' },
    { key: 'apiKey', label: 'API Schluessel', type: 'password' },
  ],
  zulip: [
    { key: 'zulipUrl', label: 'Server URL', type: 'url', placeholder: 'https://your-org.zulipchat.com' },
    { key: 'botEmail', label: 'Bot E-Mail', type: 'text' },
    { key: 'apiKey', label: 'API Schluessel', type: 'password' },
  ],
  todoist: [
    { key: 'apiToken', label: 'API Token', type: 'password' },
  ],
  freescout: [
    { key: 'apiUrl', label: 'API URL', type: 'url', placeholder: 'https://helpdesk.example.com' },
    { key: 'apiKey', label: 'API Schluessel', type: 'password' },
  ],
  nextcloud: [
    { key: 'serverUrl', label: 'Server URL', type: 'url', placeholder: 'https://cloud.example.com' },
    { key: 'username', label: 'Benutzername', type: 'text' },
    { key: 'password', label: 'Passwort', type: 'password' },
  ],
  ecodms: [
    { key: 'apiUrl', label: 'API URL', type: 'url', placeholder: 'https://ecodms.example.com' },
    { key: 'username', label: 'Benutzername', type: 'text' },
    { key: 'password', label: 'Passwort', type: 'password' },
  ],
  gembadocs: [
    { key: 'apiUrl', label: 'API URL', type: 'url', placeholder: 'https://gembadocs.example.com' },
    { key: 'apiKey', label: 'API Schluessel', type: 'password' },
  ],
};

// ============================================================
// Sub-component: single integration tab panel
// ============================================================

interface IntegrationPanelProps {
  integrationType: IntegrationType;
}

function IntegrationPanel({ integrationType }: IntegrationPanelProps) {
  const t = useTranslations('integrations');
  const { toast } = useToast();

  const meta = integrationMeta[integrationType];
  const Icon = meta.icon;
  const fields = credentialFields[integrationType];

  // ---- API queries / mutations ----
  const { data: allCredentials } = useCredentials();
  const createCredential = useCreateCredential();
  const updateCredential = useUpdateCredential();
  const testConnection = useTestCredentialConnection();
  const updateSetting = useUpdateSetting();

  // Find the saved credential for this integration type (UPPERCASE match)
  const savedCredential = allCredentials?.data.find(
    (c) => c.type === integrationType.toUpperCase(),
  ) ?? null;

  // Fetch decrypted values only when a credential exists
  const { data: credentialDetail, isLoading: isLoadingDetail } =
    useCredentialDetail(savedCredential?.id ?? null);

  // ---- Local UI state ----
  const [formData, setFormData] = useState<Record<string, string>>({});
  const [isEnabled, setIsEnabled] = useState<boolean>(
    savedCredential?.isActive ?? false,
  );
  const [visiblePasswords, setVisiblePasswords] = useState<Record<string, boolean>>({});
  const [syncInterval, setSyncInterval] = useState<string>('15');

  // Pre-fill form fields whenever decrypted credential values arrive
  useEffect(() => {
    if (credentialDetail?.credentials) {
      setFormData(
        Object.fromEntries(
          Object.entries(credentialDetail.credentials).map(([k, v]) => [k, String(v)]),
        ),
      );
    }
  }, [credentialDetail]);

  // Keep enabled toggle in sync with stored value
  useEffect(() => {
    if (savedCredential !== null) {
      setIsEnabled(savedCredential.isActive);
    }
  }, [savedCredential]);

  // ---- Handlers ----
  const handleFieldChange = (key: string, value: string) => {
    setFormData((prev) => ({ ...prev, [key]: value }));
  };

  const togglePassword = (fieldId: string) => {
    setVisiblePasswords((prev) => ({ ...prev, [fieldId]: !prev[fieldId] }));
  };

  const handleSave = async () => {
    try {
      const integrationName = t(meta.nameKey as never);

      if (!savedCredential) {
        // Create new credential
        await createCredential.mutateAsync({
          type: integrationType.toUpperCase(),
          name: 'Default',
          credentials: formData,
        });
      } else {
        // Update existing credential
        await updateCredential.mutateAsync({
          id: savedCredential.id,
          credentials: formData,
        });
      }

      toast({
        title: t('saveSettings'),
        description: t('settingsSaved' as never, { name: integrationName }),
      });
    } catch (error) {
      toast({
        title: 'Fehler beim Speichern',
        description: error instanceof Error ? error.message : 'Unbekannter Fehler',
        variant: 'destructive',
      });
    }
  };

  const handleToggleEnabled = async (checked: boolean) => {
    setIsEnabled(checked);

    if (!savedCredential) return; // Nothing to update yet

    try {
      await updateCredential.mutateAsync({
        id: savedCredential.id,
        isActive: checked,
      });
      toast({
        title: checked ? 'Integration aktiviert' : 'Integration deaktiviert',
        description: `${t(meta.nameKey as never)} wurde ${checked ? 'aktiviert' : 'deaktiviert'}.`,
      });
    } catch (error) {
      // Revert on failure
      setIsEnabled(!checked);
      toast({
        title: 'Fehler',
        description: error instanceof Error ? error.message : 'Unbekannter Fehler',
        variant: 'destructive',
      });
    }
  };

  const handleTestConnection = async () => {
    if (!savedCredential) return;

    try {
      const result = await testConnection.mutateAsync(savedCredential.id);
      toast({
        title: result.success ? t('testSuccess') : t('testFailed'),
        description: result.message,
        variant: result.success ? 'default' : 'destructive',
      });
    } catch (error) {
      toast({
        title: t('testFailed'),
        description: error instanceof Error ? error.message : t('testError'),
        variant: 'destructive',
      });
    }
  };

  const handleSyncIntervalChange = async (value: string) => {
    setSyncInterval(value);

    try {
      await updateSetting.mutateAsync({
        key: `sync.interval.${integrationType}`,
        value,
      });
    } catch {
      // Non-critical; sync interval is a best-effort setting
    }
  };

  // ---- Loading skeleton while fetching decrypted values ----
  if (savedCredential && isLoadingDetail) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-48" />
          <Skeleton className="h-4 w-64" />
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {fields.map((_, i) => (
              <Skeleton key={i} className="h-10 w-full" />
            ))}
          </div>
        </CardContent>
      </Card>
    );
  }

  const isSaving =
    createCredential.isPending || updateCredential.isPending;
  const isTesting = testConnection.isPending;
  const hasCredential = !!savedCredential;

  return (
    <Card>
      <CardHeader>
        <div className="flex items-start justify-between">
          {/* Left: icon + title */}
          <div className="flex items-center gap-3">
            <div
              className={cn(
                'flex h-10 w-10 items-center justify-center rounded-lg',
                isEnabled
                  ? 'bg-primary/10 text-primary'
                  : 'bg-muted text-muted-foreground',
              )}
            >
              <Icon className="h-5 w-5" />
            </div>
            <div>
              <CardTitle className="flex items-center gap-2">
                {t(meta.nameKey as never)}
                {/* Show status badge only when a credential is saved */}
                {hasCredential && (
                  <IntegrationStatusBadge
                    status={
                      savedCredential.syncStatus === 'SUCCESS'
                        ? 'connected'
                        : savedCredential.syncStatus === 'ERROR'
                          ? 'error'
                          : 'disconnected'
                    }
                  />
                )}
              </CardTitle>
              <CardDescription>{t(meta.descKey as never)}</CardDescription>
            </div>
          </div>

          {/* Right: enable/disable toggle */}
          <div className="flex items-center gap-2">
            <Label htmlFor={`enable-${integrationType}`}>
              {isEnabled ? t('disable') : t('enable')}
            </Label>
            <Switch
              id={`enable-${integrationType}`}
              checked={isEnabled}
              onCheckedChange={handleToggleEnabled}
            />
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Credentials section */}
        <div>
          <h3 className="mb-4 text-lg font-medium">{t('credentials')}</h3>
          <div className="grid gap-4 md:grid-cols-2">
            {fields.map((field) => {
              const fieldId = `${integrationType}-${field.key}`;
              const isPassword = field.type === 'password';
              const isVisible = visiblePasswords[fieldId];

              return (
                <div key={field.key} className="space-y-2">
                  <Label htmlFor={fieldId}>{field.label}</Label>
                  <div className="relative">
                    <Input
                      id={fieldId}
                      type={isPassword && !isVisible ? 'password' : 'text'}
                      placeholder={field.placeholder ?? (isPassword ? '••••••••' : '')}
                      value={formData[field.key] ?? ''}
                      onChange={(e) => handleFieldChange(field.key, e.target.value)}
                      className={cn(isPassword && 'pr-10')}
                    />
                    {isPassword && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className="absolute right-0 top-0 h-full px-3"
                        onClick={() => togglePassword(fieldId)}
                      >
                        {isVisible ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </Button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Sync settings section */}
        <div>
          <h3 className="mb-4 text-lg font-medium">{t('synchronization' as never)}</h3>
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor={`sync-interval-${integrationType}`}>
                {t('syncInterval')}
              </Label>
              <Select value={syncInterval} onValueChange={handleSyncIntervalChange}>
                <SelectTrigger id={`sync-interval-${integrationType}`}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">1 {t('minutes')}</SelectItem>
                  <SelectItem value="5">5 {t('minutes')}</SelectItem>
                  <SelectItem value="15">15 {t('minutes')}</SelectItem>
                  <SelectItem value="30">30 {t('minutes')}</SelectItem>
                  <SelectItem value="60">60 {t('minutes')}</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </div>
      </CardContent>

      <CardFooter className="flex justify-between border-t pt-6">
        {/* Connection test button */}
        <Button
          variant="outline"
          size="sm"
          onClick={handleTestConnection}
          disabled={!hasCredential || isTesting}
        >
          {isTesting ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              {t('testing')}
            </>
          ) : (
            t('test')
          )}
        </Button>

        {/* Save button */}
        <Button onClick={handleSave} disabled={isSaving}>
          {isSaving ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Speichern...
            </>
          ) : (
            <>
              <Settings className="mr-2 h-4 w-4" />
              {t('saveSettings')}
            </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
}

// ============================================================
// Main page component
// ============================================================

/**
 * Admin integrations management page.
 * Lists each integration as a tab; each tab loads its own credential
 * state so queries are isolated and only triggered when the tab is visited.
 */
export function AdminIntegrationsContent({ locale }: AdminIntegrationsContentProps) {
  const t = useTranslations('integrations');
  const tAdmin = useTranslations('admin');
  const { data: integrations, isLoading } = useAllIntegrationStatuses();

  const connectedCount = integrations?.filter((i) => i.status === 'connected').length ?? 0;
  const errorCount = integrations?.filter((i) => i.status === 'error').length ?? 0;

  return (
    <div className="container mx-auto space-y-8 py-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
          <Shield className="h-5 w-5 text-primary" />
        </div>
        <div>
          <h1 className="text-3xl font-bold tracking-tight">
            {tAdmin('integrationManagement')}
          </h1>
          <p className="text-muted-foreground">
            {tAdmin('integrationManagementDesc')}
          </p>
        </div>
      </div>

      {/* Loading state */}
      {isLoading ? (
        <div className="space-y-4">
          {Array.from({ length: 3 }).map((_, i) => (
            <Card key={i}>
              <CardHeader>
                <Skeleton className="h-6 w-48" />
                <Skeleton className="h-4 w-64" />
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {Array.from({ length: 3 }).map((_, j) => (
                    <Skeleton key={j} className="h-10 w-full" />
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : (
        <Tabs defaultValue="overview" className="space-y-4">
          <TabsList className="flex-wrap">
            <TabsTrigger value="overview" className="gap-2">
              <LayoutGrid className="h-4 w-4" />
              {t('overview')}
            </TabsTrigger>
            {integrations?.map((config) => {
              const meta = integrationMeta[config.type];
              const Icon = meta.icon;
              return (
                <TabsTrigger key={config.type} value={config.type} className="gap-2">
                  <Icon className="h-4 w-4" />
                  {t(meta.nameKey as never)}
                </TabsTrigger>
              );
            })}
          </TabsList>

          {/* Overview tab */}
          <TabsContent value="overview">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
              className="space-y-6"
            >
              {/* Summary Stats */}
              <div className="grid gap-4 md:grid-cols-3">
                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('allIntegrations')}</CardTitle>
                    <Plug className="h-4 w-4 text-muted-foreground" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold">{integrations?.length ?? 0}</div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('connected')}</CardTitle>
                    <CheckCircle2 className="h-4 w-4 text-green-500" />
                  </CardHeader>
                  <CardContent>
                    <div className="text-2xl font-bold text-green-500">{connectedCount}</div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <CardTitle className="text-sm font-medium">{t('error')}</CardTitle>
                    <AlertCircle className="h-4 w-4 text-destructive" />
                  </CardHeader>
                  <CardContent>
                    <div className={cn('text-2xl font-bold', errorCount > 0 && 'text-destructive')}>
                      {errorCount}
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* Integration Cards Grid */}
              <motion.div
                initial="hidden"
                animate="visible"
                variants={{
                  hidden: { opacity: 0 },
                  visible: {
                    opacity: 1,
                    transition: { staggerChildren: 0.1 },
                  },
                }}
                className="grid gap-4 md:grid-cols-2 lg:grid-cols-3"
              >
                {integrations?.map((config) => (
                  <motion.div
                    key={config.id}
                    variants={{
                      hidden: { opacity: 0, y: 20 },
                      visible: { opacity: 1, y: 0 },
                    }}
                  >
                    <IntegrationCard config={config} locale={locale} showActions={false} />
                  </motion.div>
                ))}
              </motion.div>
            </motion.div>
          </TabsContent>

          {/* Individual integration tabs */}
          {integrations?.map((config) => (
            <TabsContent key={config.type} value={config.type}>
              <motion.div
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3 }}
              >
                <IntegrationPanel integrationType={config.type} />
              </motion.div>
            </TabsContent>
          ))}
        </Tabs>
      )}
    </div>
  );
}
