'use client';

import { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import {
  Settings,
  Globe,
  RefreshCw,
  Zap,
  Building2,
  Save,
  AlertTriangle,
} from 'lucide-react';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/hooks/use-toast';
import {
  useSystemSettings,
  useUpdateSetting,
  useBulkUpdateSettings,
  type SystemSetting,
} from '@/hooks/use-system-settings';

// ---------------------------------------------------------------------------
// Types & constants
// ---------------------------------------------------------------------------

interface SystemSettingsContentProps {
  locale: string;
}

/** Integration types that appear in sync settings */
const INTEGRATION_TYPES = [
  'plentyone',
  'zulip',
  'todoist',
  'freescout',
  'nextcloud',
  'ecodms',
  'gembadocs',
] as const;

const SYNC_INTERVAL_OPTIONS = ['1', '5', '10', '15', '30', '60'] as const;

// ---------------------------------------------------------------------------
// Helper: build a lookup map from the flat settings array
// ---------------------------------------------------------------------------

function buildSettingsMap(settings: SystemSetting[]): Record<string, string> {
  return settings.reduce<Record<string, string>>((acc, s) => {
    acc[s.key] = s.value;
    return acc;
  }, {});
}

// ---------------------------------------------------------------------------
// Loading skeleton
// ---------------------------------------------------------------------------

function SettingsSkeleton() {
  return (
    <div className="space-y-6">
      <Skeleton className="h-10 w-96" />
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-48" />
          <Skeleton className="h-4 w-72" />
        </CardHeader>
        <CardContent className="space-y-4">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="space-y-2">
              <Skeleton className="h-4 w-32" />
              <Skeleton className="h-10 w-full" />
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------

/**
 * Admin page for managing global system settings.
 * Groups settings by category into tabs: Branding, CORS, Sync, Features.
 */
export function SystemSettingsContent({ locale: _locale }: SystemSettingsContentProps) {
  const t = useTranslations('systemSettings');
  const { toast } = useToast();

  const { data, isLoading } = useSystemSettings();
  const updateSetting = useUpdateSetting();
  const bulkUpdate = useBulkUpdateSettings();

  // Local form state keyed by setting key
  const [formValues, setFormValues] = useState<Record<string, string>>({});

  // Populate form values once data is loaded
  useEffect(() => {
    if (data?.settings) {
      setFormValues(buildSettingsMap(data.settings));
    }
  }, [data]);

  // -------------------------------------------------------------------------
  // Generic helpers
  // -------------------------------------------------------------------------

  function handleChange(key: string, value: string) {
    setFormValues((prev) => ({ ...prev, [key]: value }));
  }

  async function handleBulkSave(keys: string[]) {
    const settings = keys.map((key) => ({ key, value: formValues[key] ?? '' }));

    try {
      await bulkUpdate.mutateAsync({ settings });
      toast({ title: t('saved') });
    } catch {
      toast({ title: t('saveError'), variant: 'destructive' });
    }
  }

  async function handleSingleToggle(key: string, checked: boolean) {
    const value = checked ? 'true' : 'false';
    handleChange(key, value);

    try {
      await updateSetting.mutateAsync({ key, value });
      toast({ title: t('saved') });
    } catch {
      toast({ title: t('saveError'), variant: 'destructive' });
    }
  }

  // -------------------------------------------------------------------------
  // Render
  // -------------------------------------------------------------------------

  return (
    <div className="container mx-auto space-y-8 py-6">
      {/* Page header */}
      <motion.div
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3 }}
        className="flex items-center gap-3"
      >
        <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
          <Settings className="h-5 w-5 text-primary" />
        </div>
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{t('title')}</h1>
          <p className="text-muted-foreground">{t('description')}</p>
        </div>
      </motion.div>

      {/* Content */}
      {isLoading ? (
        <SettingsSkeleton />
      ) : (
        <Tabs defaultValue="branding" className="space-y-4">
          <TabsList>
            <TabsTrigger value="branding" className="gap-2">
              <Building2 className="h-4 w-4" />
              {t('branding')}
            </TabsTrigger>
            <TabsTrigger value="cors" className="gap-2">
              <Globe className="h-4 w-4" />
              {t('cors')}
            </TabsTrigger>
            <TabsTrigger value="sync" className="gap-2">
              <RefreshCw className="h-4 w-4" />
              {t('sync')}
            </TabsTrigger>
            <TabsTrigger value="features" className="gap-2">
              <Zap className="h-4 w-4" />
              {t('features')}
            </TabsTrigger>
          </TabsList>

          {/* ---------------------------------------------------------------- */}
          {/* Branding tab                                                     */}
          {/* ---------------------------------------------------------------- */}
          <TabsContent value="branding">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle>{t('branding')}</CardTitle>
                  <CardDescription>{t('description')}</CardDescription>
                </CardHeader>

                <CardContent className="space-y-6">
                  <div className="grid gap-4 md:grid-cols-2">
                    {/* App name */}
                    <div className="space-y-2">
                      <Label htmlFor="branding-appName">{t('appName')}</Label>
                      <Input
                        id="branding-appName"
                        value={formValues['branding.appName'] ?? ''}
                        onChange={(e) => handleChange('branding.appName', e.target.value)}
                        placeholder="tOS"
                      />
                    </div>

                    {/* Company name */}
                    <div className="space-y-2">
                      <Label htmlFor="branding-companyName">{t('companyName')}</Label>
                      <Input
                        id="branding-companyName"
                        value={formValues['branding.companyName'] ?? ''}
                        onChange={(e) => handleChange('branding.companyName', e.target.value)}
                        placeholder="Mein Unternehmen GmbH"
                      />
                    </div>

                    {/* Logo URL */}
                    <div className="space-y-2 md:col-span-2">
                      <Label htmlFor="branding-logoUrl">{t('logoUrl')}</Label>
                      <Input
                        id="branding-logoUrl"
                        type="url"
                        value={formValues['branding.logoUrl'] ?? ''}
                        onChange={(e) => handleChange('branding.logoUrl', e.target.value)}
                        placeholder="https://example.com/logo.png"
                      />
                    </div>
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() =>
                        handleBulkSave([
                          'branding.appName',
                          'branding.companyName',
                          'branding.logoUrl',
                        ])
                      }
                      disabled={bulkUpdate.isPending}
                    >
                      <Save className="mr-2 h-4 w-4" />
                      {t('save')}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* ---------------------------------------------------------------- */}
          {/* CORS tab                                                         */}
          {/* ---------------------------------------------------------------- */}
          <TabsContent value="cors">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle>{t('cors')}</CardTitle>
                  <CardDescription>{t('corsOriginsDesc')}</CardDescription>
                </CardHeader>

                <CardContent className="space-y-6">
                  <div className="space-y-2">
                    <Label htmlFor="cors-origins">{t('corsOrigins')}</Label>
                    <Textarea
                      id="cors-origins"
                      rows={6}
                      value={(formValues['cors.origins'] ?? '')
                        .split(',')
                        .map((s) => s.trim())
                        .join('\n')}
                      onChange={(e) => {
                        // Store as comma-separated
                        const joined = e.target.value
                          .split('\n')
                          .map((s) => s.trim())
                          .filter(Boolean)
                          .join(',');
                        handleChange('cors.origins', joined);
                      }}
                      placeholder="https://app.example.com&#10;http://localhost:3000"
                      className="font-mono text-sm"
                    />
                    <p className="text-xs text-muted-foreground">
                      Einen Origin pro Zeile eingeben.
                    </p>
                  </div>

                  {/* Restart notice */}
                  <div className="flex items-center gap-2 rounded-md bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:bg-amber-950/30 dark:text-amber-400">
                    <AlertTriangle className="h-4 w-4 shrink-0" />
                    <span>{t('requiresRestart')}</span>
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() => handleBulkSave(['cors.origins'])}
                      disabled={bulkUpdate.isPending}
                    >
                      <Save className="mr-2 h-4 w-4" />
                      {t('save')}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* ---------------------------------------------------------------- */}
          {/* Sync tab                                                         */}
          {/* ---------------------------------------------------------------- */}
          <TabsContent value="sync">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle>{t('sync')}</CardTitle>
                  <CardDescription>{t('enableSyncJobsDesc')}</CardDescription>
                </CardHeader>

                <CardContent className="space-y-6">
                  <div className="grid gap-6 md:grid-cols-2">
                    {INTEGRATION_TYPES.map((type) => {
                      const settingKey = `sync.interval.${type}`;
                      const currentValue = formValues[settingKey] ?? '15';

                      return (
                        <div key={type} className="space-y-2">
                          <Label htmlFor={`sync-${type}`} className="capitalize">
                            {type}
                          </Label>
                          <div className="flex items-center gap-2">
                            <Select
                              value={currentValue}
                              onValueChange={(val) => handleChange(settingKey, val)}
                            >
                              <SelectTrigger id={`sync-${type}`} className="w-32">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {SYNC_INTERVAL_OPTIONS.map((opt) => (
                                  <SelectItem key={opt} value={opt}>
                                    {opt} {t('minutes')}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  <Separator />

                  <div className="flex justify-end">
                    <Button
                      onClick={() =>
                        handleBulkSave(
                          INTEGRATION_TYPES.map((type) => `sync.interval.${type}`),
                        )
                      }
                      disabled={bulkUpdate.isPending}
                    >
                      <Save className="mr-2 h-4 w-4" />
                      {t('save')}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>

          {/* ---------------------------------------------------------------- */}
          {/* Features tab                                                     */}
          {/* ---------------------------------------------------------------- */}
          <TabsContent value="features">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3 }}
            >
              <Card>
                <CardHeader>
                  <CardTitle>{t('features')}</CardTitle>
                  <CardDescription>{t('description')}</CardDescription>
                </CardHeader>

                <CardContent className="space-y-6">
                  {/* Sync jobs toggle */}
                  <div className="flex items-center justify-between gap-4 rounded-lg border p-4">
                    <div className="space-y-1">
                      <Label htmlFor="feature-syncJobs" className="text-sm font-medium">
                        {t('enableSyncJobs')}
                      </Label>
                      <p className="text-sm text-muted-foreground">{t('enableSyncJobsDesc')}</p>
                    </div>
                    <Switch
                      id="feature-syncJobs"
                      checked={formValues['feature.syncJobs.enabled'] === 'true'}
                      onCheckedChange={(checked) =>
                        handleSingleToggle('feature.syncJobs.enabled', checked)
                      }
                      disabled={updateSetting.isPending}
                    />
                  </div>

                  {/* Swagger toggle */}
                  <div className="flex items-center justify-between gap-4 rounded-lg border p-4">
                    <div className="space-y-1">
                      <Label htmlFor="feature-swagger" className="text-sm font-medium">
                        {t('enableSwagger')}
                      </Label>
                      <p className="text-sm text-muted-foreground">{t('enableSwaggerDesc')}</p>
                      <div className="flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400">
                        <AlertTriangle className="h-3 w-3" />
                        <span>{t('requiresRestart')}</span>
                      </div>
                    </div>
                    <Switch
                      id="feature-swagger"
                      checked={formValues['feature.swagger.enabled'] === 'true'}
                      onCheckedChange={(checked) =>
                        handleSingleToggle('feature.swagger.enabled', checked)
                      }
                      disabled={updateSetting.isPending}
                    />
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
