import React from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { RefreshCcw, PlugZap, RefreshCw, ShieldCheck, Copy, Power, Clock3 } from 'lucide-react';
import { YStack, XStack } from '@tamagui/stacks';
import { SizableText as Text } from '@tamagui/text';
import { Pressable } from '@tamagui/react-native-web-lite';
import { useTheme } from '@tamagui/core';
import { MobileShell } from './components/MobileShell';
import { MobileCard, CTAButton, PillBadge } from './components/Primitives';
import {
  getEvent,
  getEventPhotoboothStatus,
  enableEventPhotobooth,
  disableEventPhotobooth,
  rotateEventPhotobooth,
  PhotoboothStatus,
  TenantEvent,
} from '../api';
import { isAuthError } from '../auth/tokens';
import { getApiErrorMessage } from '../lib/apiError';
import { formatEventDate, resolveEventDisplayName } from '../lib/events';
import toast from 'react-hot-toast';

export default function MobileEventPhotoboothPage() {
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const slug = slugParam ?? null;
  const navigate = useNavigate();
  const { t, i18n } = useTranslation('management');
  const theme = useTheme();
  const text = String(theme.color?.val ?? '#111827');
  const muted = String(theme.gray?.val ?? '#4b5563');
  const border = String(theme.borderColor?.val ?? '#e5e7eb');
  const surface = String(theme.surface?.val ?? '#ffffff');

  const [event, setEvent] = React.useState<TenantEvent | null>(null);
  const [status, setStatus] = React.useState<PhotoboothStatus | null>(null);
  const [loading, setLoading] = React.useState(true);
  const [updating, setUpdating] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const locale = i18n.language?.startsWith('en') ? 'en-GB' : 'de-DE';

  const load = React.useCallback(async () => {
    if (!slug) return;
    setLoading(true);
    setError(null);
    try {
      const [eventData, statusData] = await Promise.all([getEvent(slug), getEventPhotoboothStatus(slug)]);
      setEvent(eventData);
      setStatus(statusData);
    } catch (err) {
      if (!isAuthError(err)) {
        setError(getApiErrorMessage(err, t('management.photobooth.errors.loadFailed', 'Photobooth-Link konnte nicht geladen werden.')));
      }
    } finally {
      setLoading(false);
    }
  }, [slug, t]);

  React.useEffect(() => {
    void load();
  }, [load]);

  const handleEnable = async (mode?: 'ftp' | 'sparkbooth') => {
    if (!slug) return;
    setUpdating(true);
    try {
      const result = await enableEventPhotobooth(slug, { mode: mode ?? status?.mode ?? 'ftp' });
      setStatus(result);
      toast.success(t('management.photobooth.actions.enable', 'Zugang aktiviert'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(getApiErrorMessage(err, t('management.photobooth.errors.enableFailed', 'Zugang konnte nicht aktiviert werden.')));
      }
    } finally {
      setUpdating(false);
    }
  };

  const handleDisable = async () => {
    if (!slug) return;
    setUpdating(true);
    try {
      const result = await disableEventPhotobooth(slug, { mode: status?.mode ?? 'ftp' });
      setStatus(result);
      toast.success(t('management.photobooth.actions.disable', 'Zugang deaktiviert'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(getApiErrorMessage(err, t('management.photobooth.errors.disableFailed', 'Zugang konnte nicht deaktiviert werden.')));
      }
    } finally {
      setUpdating(false);
    }
  };

  const handleRotate = async () => {
    if (!slug) return;
    setUpdating(true);
    try {
      const result = await rotateEventPhotobooth(slug, { mode: status?.mode ?? 'ftp' });
      setStatus(result);
      toast.success(t('management.photobooth.presets.actions.rotate', 'Zugang zurückgesetzt'));
    } catch (err) {
      if (!isAuthError(err)) {
        toast.error(getApiErrorMessage(err, t('management.photobooth.errors.rotateFailed', 'Zugangsdaten konnten nicht neu generiert werden.')));
      }
    } finally {
      setUpdating(false);
    }
  };

  const modeLabel =
    status?.mode === 'sparkbooth'
      ? t('photobooth.credentials.sparkboothTitle', 'Sparkbooth / HTTP')
      : t('photobooth.credentials.heading', 'FTP (Classic)');

  const isActive = Boolean(status?.enabled);
  const title = event ? resolveEventDisplayName(event) : t('management.header.appName', 'Event Admin');
  const subtitle =
    event?.event_date ? formatEventDate(event.event_date, locale) : t('header.selectEvent', 'Select an event to continue');

  return (
    <MobileShell
      activeTab="home"
      title={title}
      subtitle={subtitle ?? undefined}
      onBack={() => navigate(-1)}
      headerActions={
        <Pressable onPress={() => load()}>
          <RefreshCcw size={18} color={text} />
        </Pressable>
      }
    >
      {error ? (
        <MobileCard>
          <Text fontWeight="700" color="#b91c1c">
            {error}
          </Text>
        </MobileCard>
      ) : null}

      {loading ? (
        <YStack space="$2">
          {Array.from({ length: 3 }).map((_, idx) => (
            <MobileCard key={`ph-skel-${idx}`} height={110} opacity={0.6} />
          ))}
        </YStack>
      ) : (
        <YStack space="$2">
          <MobileCard space="$2">
            <XStack justifyContent="space-between" alignItems="center">
              <YStack space="$1">
                <Text fontSize="$md" fontWeight="800" color={text}>
                  {t('photobooth.title', 'Photobooth')}
                </Text>
                <Text fontSize="$xs" color={muted}>
                  {t('photobooth.credentials.description', 'Share these credentials with your photobooth software.')}
                </Text>
                <Text fontSize="$xs" color={muted}>
                  {t('photobooth.mode.active', 'Current: {{mode}}', { mode: modeLabel })}
                </Text>
              </YStack>
              <PillBadge tone={isActive ? 'success' : 'warning'}>
                {isActive ? t('photobooth.status.badgeActive', 'ACTIVE') : t('photobooth.status.badgeInactive', 'INACTIVE')}
              </PillBadge>
            </XStack>
            <XStack space="$2" marginTop="$2" flexWrap="nowrap">
              <XStack flex={1} minWidth={0}>
                <CTAButton
                  label={t('photobooth.credentials.heading', 'FTP credentials')}
                  tone={status?.mode === 'ftp' ? 'primary' : 'ghost'}
                  onPress={() => handleEnable('ftp')}
                  disabled={updating}
                  style={{ width: '100%', paddingHorizontal: 10, paddingVertical: 10 }}
                />
              </XStack>
              <XStack flex={1} minWidth={0}>
                <CTAButton
                  label={t('photobooth.credentials.sparkboothTitle', 'Sparkbooth upload (HTTP)')}
                  tone={status?.mode === 'sparkbooth' ? 'primary' : 'ghost'}
                  onPress={() => handleEnable('sparkbooth')}
                  disabled={updating}
                  style={{ width: '100%', paddingHorizontal: 10, paddingVertical: 10 }}
                />
              </XStack>
            </XStack>
          </MobileCard>

          <MobileCard space="$2">
            <Text fontSize="$sm" fontWeight="700" color={text}>
              {t('photobooth.credentials.heading', 'FTP credentials')}
            </Text>
            <YStack space="$1">
              <CredentialRow label={t('photobooth.credentials.host', 'Host')} value={status?.host ?? '—'} border={border} />
              <CredentialRow label={t('photobooth.credentials.username', 'Username')} value={status?.username ?? '—'} border={border} />
              <CredentialRow label={t('photobooth.credentials.password', 'Password')} value={status?.password ?? '—'} border={border} masked />
              {status?.upload_url ? <CredentialRow label={t('photobooth.credentials.postUrl', 'Upload URL')} value={status.upload_url} border={border} /> : null}
            </YStack>
            <XStack space="$2" marginTop="$2" flexWrap="nowrap">
              <XStack flex={1} minWidth={0}>
                <CTAButton
                  label={updating ? t('common.processing', '...') : t('photobooth.actions.rotate', 'Regenerate access')}
                  onPress={() => handleRotate()}
                  iconLeft={<RefreshCw size={14} color={surface} />}
                  style={{ width: '100%', paddingHorizontal: 10, paddingVertical: 10 }}
                />
              </XStack>
              <XStack flex={1} minWidth={0}>
                <CTAButton
                  label={isActive ? t('photobooth.actions.disable', 'Disable') : t('photobooth.actions.enable', 'Activate photobooth')}
                  onPress={() => (isActive ? handleDisable() : handleEnable())}
                  tone={isActive ? 'ghost' : 'primary'}
                  iconLeft={isActive ? <Power size={14} color={text} /> : <PlugZap size={14} color={surface} />}
                  disabled={updating}
                  style={{ width: '100%', paddingHorizontal: 10, paddingVertical: 10 }}
                />
              </XStack>
            </XStack>
          </MobileCard>

          <MobileCard space="$2">
            <Text fontSize="$sm" fontWeight="700" color={text}>
              {t('photobooth.status.heading', 'Status')}
            </Text>
            <YStack space="$1">
              <StatusRow icon={<ShieldCheck size={16} color={text} />} label={t('photobooth.status.mode', 'Mode')} value={modeLabel} />
              <StatusRow
                icon={<PlugZap size={16} color={text} />}
                label={t('photobooth.status.heading', 'Status')}
                value={isActive ? t('common.enabled', 'Enabled') : t('common.disabled', 'Disabled')}
              />
              {status?.metrics?.uploads_last_hour != null ? (
                <StatusRow
                  icon={<RefreshCcw size={16} color={text} />}
                  label={t('photobooth.rateLimit.usage', 'Uploads last hour')}
                  value={String(status.metrics.uploads_last_hour)}
                />
              ) : null}
              {status?.metrics?.last_upload_at ? (
                <StatusRow
                  icon={<Clock3 size={16} color={text} />}
                  label={t('photobooth.stats.lastUpload', 'Letzter Upload')}
                  value={formatEventDate(status.metrics.last_upload_at, locale) ?? '—'}
                />
              ) : null}
            </YStack>
          </MobileCard>
        </YStack>
      )}
    </MobileShell>
  );
}

function CredentialRow({ label, value, border, masked }: { label: string; value: string; border: string; masked?: boolean }) {
  const { t } = useTranslation('management');
  return (
    <XStack alignItems="center" justifyContent="space-between" borderWidth={1} borderColor={border} borderRadius="$3" padding="$2">
      <YStack>
        <Text fontSize="$xs" color="#6b7280">
          {label}
        </Text>
        <Text fontSize="$sm" fontWeight="700" color="#111827">
          {masked ? '••••••••' : value}
        </Text>
      </YStack>
      <Pressable
        onPress={async () => {
          try {
            await navigator.clipboard.writeText(value);
            toast.success(t('common.copied', 'Kopiert'));
          } catch {
            toast.error(t('common.copyFailed', 'Kopieren fehlgeschlagen'));
          }
        }}
      >
        <Copy size={16} color="#6b7280" />
      </Pressable>
    </XStack>
  );
}

function StatusRow({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <XStack alignItems="center" justifyContent="space-between">
      <XStack alignItems="center" space="$2">
        {icon}
        <Text fontSize="$sm" color="#111827">
          {label}
        </Text>
      </XStack>
      <Text fontSize="$sm" fontWeight="700" color="#111827">
        {value}
      </Text>
    </XStack>
  );
}
