import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { Activity, Bell, CalendarDays, Camera, CheckCircle2, ChevronDown, Download, Image as ImageIcon, Layout, ListTodo, MapPin, Megaphone, MessageCircle, Pencil, QrCode, Settings, ShieldCheck, Smartphone, Sparkles, TrendingUp, Tv, Users, ArrowRight, Play, Clock, AlertCircle } 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 { Image } from '@tamagui/image';
import { isSameDay, isPast, isFuture, parseISO, differenceInDays, startOfDay } from 'date-fns';

import { MobileShell } from './components/MobileShell';
import { ADMIN_EVENTS_PATH, adminPath } from '../constants';
import { useEventContext } from '../context/EventContext';
import { getEventStats, EventStats, TenantEvent, getEventPhotos, TenantPhoto } from '../api';
import { formatEventDate, resolveEventDisplayName } from '../lib/events';
import { useAuth } from '../auth/context';
import { useAdminTheme } from './theme';
import { buildLimitWarnings } from '../lib/limitWarnings';
import { withAlpha } from './components/colors';
import { useEventReadiness } from './hooks/useEventReadiness';
import { SetupChecklist } from './components/SetupChecklist';
import { KpiStrip } from './components/Primitives';

// --- HELPERS ---

function translateLimits(t: any) {
  return (key: string, options?: any) => t(`management:limits.${key}`, key, options);
}

// --- MODERN PRIMITIVES ---

function ModernCard({ children, style, ...rest }: any) {
  const theme = useAdminTheme();
  return (
    <YStack
      backgroundColor={theme.surface}
      borderRadius={theme.cardRadius || 16}
      borderWidth={1}
      borderColor={theme.border}
      padding="$3.5"
      space="$2"
      style={{
        boxShadow: `0 2px 8px ${theme.shadow}`,
        ...style
      }}
      {...rest}
    >
      {children}
    </YStack>
  );
}

function ModernButton({ label, onPress, tone = 'primary', fullWidth = true, icon, style }: any) {
  const theme = useAdminTheme();
  const isPrimary = tone === 'primary';
  const isGhost = tone === 'ghost';
  const isAccent = tone === 'accent';
  
  const bg = isPrimary ? theme.primary : isAccent ? theme.accent : isGhost ? 'transparent' : theme.surface;
  const text = isPrimary || isAccent ? 'white' : isGhost ? theme.text : theme.textStrong;
  const border = isPrimary || isAccent || isGhost ? 'transparent' : theme.border;

  return (
    <Pressable
      onPress={onPress}
      style={{
        width: fullWidth ? '100%' : undefined,
        flex: fullWidth ? undefined : 1,
        ...style
      }}
    >
      <XStack
        height={48}
        borderRadius={12}
        alignItems="center"
        justifyContent="center"
        backgroundColor={bg}
        borderWidth={1}
        borderColor={border}
        space="$2"
      >
        {icon}
        <Text fontSize="$sm" fontWeight="700" color={text}>
          {label}
        </Text>
      </XStack>
    </Pressable>
  );
}

function StatusBadge({ status }: { status: string }) {
  const theme = useAdminTheme();
  const { t } = useTranslation('management');
  
  const config = {
    published: { bg: '#DCFCE7', text: '#166534', label: t('events.status.published', 'Live') }, 
    draft: { bg: '#FEF3C7', text: '#92400E', label: t('events.status.draft', 'Draft') }, 
    archived: { bg: '#F1F5F9', text: '#475569', label: t('events.status.archived', 'Archived') },
  }[status] || { bg: theme.surfaceMuted, text: theme.muted, label: status };

  return (
    <XStack
      paddingHorizontal="$2"
      paddingVertical="$1"
      borderRadius={6}
      backgroundColor={config.bg}
    >
      <Text fontSize="$xs" fontWeight="700" color={config.text}>
        {config.label}
      </Text>
    </XStack>
  );
}

// --- MAIN PAGE COMPONENT ---

export default function MobileDashboardPage() {
  const navigate = useNavigate();
  const { slug: slugParam } = useParams<{ slug?: string }>();
  const { t, i18n } = useTranslation(['management', 'dashboard', 'mobile']);
  const { events, activeEvent, hasEvents, hasMultipleEvents, isLoading, selectEvent } = useEventContext();
  const { user } = useAuth();
  const isMember = user?.role === 'member';

  // --- LOGIC ---
  const memberPermissions = React.useMemo(() => {
    if (!isMember) return ['*'];
    return Array.isArray(activeEvent?.member_permissions) ? activeEvent?.member_permissions ?? [] : [];
  }, [activeEvent?.member_permissions, isMember]);
  
  function allowPermission(permissions: string[], permission: string): boolean {
    if (permissions.includes('*') || permissions.includes(permission)) return true;
    if (permission.includes(':')) {
      const [prefix] = permission.split(':');
      return permissions.includes(`${prefix}:*`);
    }
    return false;
  }
  
  const canManageEvents = React.useMemo(() => allowPermission(memberPermissions, 'events:manage'), [memberPermissions]);
  
  const { data: stats } = useQuery<EventStats | null>({
    queryKey: ['mobile', 'dashboard', 'stats', activeEvent?.slug],
    enabled: Boolean(activeEvent?.slug),
    queryFn: async () => {
      if (!activeEvent?.slug) return null;
      return await getEventStats(activeEvent.slug);
    },
  });

  const { data: photoData } = useQuery({
    queryKey: ['mobile', 'dashboard', 'recent-photos', activeEvent?.slug],
    enabled: Boolean(activeEvent?.slug),
    queryFn: async () => {
      if (!activeEvent?.slug) return { photos: [] };
      return await getEventPhotos(activeEvent.slug, { perPage: 6, sort: 'desc' });
    },
  });

  const locale = i18n.language?.startsWith('en') ? 'en-GB' : 'de-DE';
  
  React.useEffect(() => {
    if (!slugParam || slugParam === activeEvent?.slug) return;
    selectEvent(slugParam);
  }, [activeEvent?.slug, selectEvent, slugParam]);

  const shouldRedirectToSelector = !isLoading && !activeEvent && !slugParam;

  React.useEffect(() => {
    if (!shouldRedirectToSelector) return;
    navigate(ADMIN_EVENTS_PATH, { replace: true });
  }, [navigate, shouldRedirectToSelector]);

  const [eventSwitcherOpen, setEventSwitcherOpen] = React.useState(false);
  
  // --- RENDER ---
  
  if (shouldRedirectToSelector) {
    return null;
  }

  if (isLoading) {
    return (
      <MobileShell activeTab="home" title={t('mobileDashboard.title', 'Dashboard')}>
        <ModernCard height={120} />
      </MobileShell>
    );
  }

  if (!hasEvents && !events.length) {
     return (
        <MobileShell activeTab="home" title={t('mobileDashboard.title', 'Dashboard')}>
           <EmptyState canManage={canManageEvents} onCreate={() => navigate(adminPath('/mobile/events/new'))} />
        </MobileShell>
     );
  }

  // Calculate Readiness
  const readiness = useEventReadiness(activeEvent, t as any);
  const phase = activeEvent ? getEventPhase(activeEvent) : 'setup';
  const isCompleted = phase === 'post';

  return (
    <MobileShell activeTab="home" title={t('mobileDashboard.title', 'Dashboard')}>
      
      {/* 1. LIFECYCLE HERO */}
      <LifecycleHero
        event={activeEvent}
        stats={stats}
        locale={locale}
        navigate={navigate}
        onSwitch={() => setEventSwitcherOpen(true)}
        canSwitch={hasMultipleEvents}
        readiness={readiness}
      />

      {/* 1b. SETUP CHECKLIST */}
      {phase === 'setup' && (
         <SetupChecklist 
            steps={readiness.steps} 
            title={t('management:photobooth.checklist.title', 'Checklist')} 
         />
      )}

      {/* 2. PULSE STRIP */}
      <PulseStrip event={activeEvent} stats={stats} />

      {/* 3. ALERTS */}
      <AlertsSection event={activeEvent} stats={stats} t={t} />

      {/* 4. UNIFIED COMMAND GRID */}
      <UnifiedToolGrid 
         event={activeEvent} 
         navigate={navigate}
         permissions={memberPermissions}
         isMember={isMember}
         isCompleted={isCompleted}
      />

      {/* 5. RECENT PHOTOS */}
      <RecentPhotosSection 
         photos={photoData?.photos ?? []} 
         navigate={navigate} 
         slug={activeEvent?.slug} 
      />

    </MobileShell>
  );
}

// --- SUB COMPONENTS ---

type EventPhase = 'setup' | 'live' | 'post';

function getEventPhase(event: TenantEvent): EventPhase {
  if (event.status === 'archived') return 'post';
  if (!event.event_date) return 'setup';
  const today = startOfDay(new Date());
  const eventDate = parseISO(event.event_date);
  if (isSameDay(today, eventDate)) return 'live';
  if (isPast(eventDate)) return 'post';
  return 'setup';
}

function LifecycleHero({ event, stats, locale, navigate, onSwitch, canSwitch, readiness }: any) {
  const theme = useAdminTheme();
  const { t } = useTranslation(['management', 'dashboard']);
  
  if (!event) return null;
  const phase = getEventPhase(event);
  const pendingPhotos = stats?.pending_photos ?? event.pending_photo_count ?? 0;
  
  // Header Row
  const Header = () => (
     <XStack alignItems="center" justifyContent="space-between" marginBottom="$3">
        <YStack>
           <Text fontSize="$xs" color={theme.muted} fontWeight="600" textTransform="uppercase" letterSpacing={1}>
              {formatEventDate(event.event_date, locale)}
           </Text>
        </YStack>
        <StatusBadge status={event.status} />
     </XStack>
  );

  if (phase === 'live') {
    return (
      <YStack>
         <Header />
         <ModernCard 
            backgroundColor={theme.primary} 
            borderWidth={0} 
            style={{ backgroundImage: 'linear-gradient(135deg, #4F46E5 0%, #4338CA 100%)' }}
         >
            <XStack alignItems="center" justifyContent="space-between">
               <YStack space="$1">
                  <XStack alignItems="center" space="$2">
                    <YStack width={8} height={8} borderRadius={4} backgroundColor="#22C55E" />
                    <Text color="white" fontWeight="700" fontSize="$xs" textTransform="uppercase" letterSpacing={1}>
                      {t('dashboard:liveNow.status', 'Happening Now')}
                    </Text>
                  </XStack>
                  <Text color="white" fontSize="$lg" fontWeight="800">
                     {pendingPhotos > 0 ? `${pendingPhotos} ${t('management:photos.filters.pending', 'Pending')}` : t('dashboard:liveNow.description', 'Event is Running')}
                  </Text>
               </YStack>
               {pendingPhotos > 0 && (
                 <Pressable onPress={() => navigate(adminPath(`/mobile/events/${event.slug}/control-room`))}>
                    <YStack backgroundColor="white" borderRadius={999} paddingHorizontal="$3" paddingVertical="$2">
                       <Text fontSize="$xs" fontWeight="800" color={theme.primary}>
                         {t('management:photos.openModeration', 'Review')}
                       </Text>
                    </YStack>
                 </Pressable>
               )}
            </XStack>
         </ModernCard>
      </YStack>
    );
  }

  const daysToGo = event.event_date ? differenceInDays(parseISO(event.event_date), new Date()) : 0;
  
  if (phase === 'post') {
     return (
        <YStack>
           <Header />
           <ModernCard space="$3">
              <XStack alignItems="center" space="$2.5">
                 <YStack width={40} height={40} borderRadius={20} backgroundColor={theme.success} alignItems="center" justifyContent="center">
                    <CheckCircle2 size={20} color="white" />
                 </YStack>
                 <YStack>
                    <Text fontSize="$md" fontWeight="800" color={theme.textStrong}>
                      {t('events.recap.completedTitle', 'Event completed')}
                    </Text>
                    <Text fontSize="$xs" color={theme.muted}>{t('events.recap.galleryOpen', 'Gallery online')}</Text>
                 </YStack>
              </XStack>
              <ModernButton 
                 label={t('events.recap.downloadAll', 'Download photos')}
                 tone="primary" 
                 icon={<Download size={16} color="white" />}
                 onPress={() => navigate(adminPath(`/mobile/exports`))}
              />
              <ModernButton
                label={t('events.recap.openRecap', 'Open recap')}
                tone="ghost"
                icon={<ArrowRight size={16} color={theme.text} />}
                onPress={() => navigate(adminPath(`/mobile/events/${event.slug}/recap`))}
              />
           </ModernCard>
        </YStack>
     );
  }

  // SETUP
  const nextStep = readiness.nextStep;
  const ctaLabel = nextStep ? nextStep.ctaLabel : t('dashboard:onboarding.hero.cta', 'Setup Complete');
  const ctaAction = nextStep ? () => navigate(adminPath(nextStep.targetPath)) : undefined;
  
  return (
    <YStack>
       <Header />
       <ModernCard space="$3">
          <XStack alignItems="center" justifyContent="space-between">
             <YStack>
                <Text fontSize="$xs" color={theme.muted} fontWeight="700" textTransform="uppercase">
                  {t('dashboard:upcoming.status.planning', 'Countdown')}
                </Text>
                <Text fontSize="$2xl" fontWeight="900" color={theme.primary}>
                   {daysToGo} <Text fontSize="$sm" color={theme.muted} fontWeight="500">{t('management:galleryStatus.daysLabel', 'days')}</Text>
                </Text>
             </YStack>
             <YStack width={48} height={48} borderRadius={24} backgroundColor={theme.surfaceMuted} alignItems="center" justifyContent="center">
                <CalendarDays size={24} color={theme.primary} />
             </YStack>
          </XStack>
          
          <YStack height={1} backgroundColor={theme.border} />
          
          {/* Main CTA if not ready */}
          {!readiness.isReady && (
             <ModernButton 
                label={ctaLabel} 
                tone='primary'
                icon={<ArrowRight size={16} color="white" />}
                onPress={ctaAction}
             />
          )}
          {readiness.isReady && (
             <XStack alignItems="center" space="$2">
                <CheckCircle2 size={18} color={theme.successText} />
                <Text fontSize="$sm" color={theme.successText} fontWeight="700">Ready for Liftoff</Text>
             </XStack>
          )}
       </ModernCard>
    </YStack>
  );
}

function PulseStrip({ event, stats }: any) {
  const theme = useAdminTheme();
  const { t } = useTranslation('management');
  const uploadCount = stats?.uploads_total ?? event?.photo_count ?? 0;
  const guestCount = event?.active_invites_count ?? event?.total_invites_count ?? 0;
  const pendingCount = stats?.pending_photos ?? event?.pending_photo_count ?? 0;

  return (
    <YStack paddingVertical="$1">
       <KpiStrip items={[
         {
            icon: ImageIcon,
            value: uploadCount,
            label: t('management:events.list.stats.photos', 'Photos'),
            color: theme.primary
         },
         {
            icon: Users,
            value: guestCount,
            label: t('management:events.list.stats.guests', 'Guests'),
            color: theme.textStrong
         },
         {
            icon: ShieldCheck,
            value: pendingCount,
            label: t('management:photos.filters.pending', 'Pending'),
            note: pendingCount > 0 ? t('management:common.actionNeeded', 'Review') : undefined,
            color: pendingCount > 0 ? '#8B5CF6' : theme.textMuted
         }
       ]} />
    </YStack>
  );
}

function UnifiedToolGrid({ event, navigate, permissions, isMember, isCompleted }: any) {
  const theme = useAdminTheme();
  const { t } = useTranslation(['management', 'dashboard']);
  const slug = event?.slug;
  if (!slug) return null;

  const experienceItems = [
    { label: t('management:photos.gallery.title', 'Photos'), icon: ImageIcon, path: `/mobile/events/${slug}/control-room`, color: theme.primary },
    !isCompleted ? { label: t('management:events.quick.liveShowSettings', 'Slide Show'), icon: Tv, path: `/mobile/events/${slug}/live-show/settings`, color: '#F59E0B' } : null,
    !isCompleted ? { label: t('events.tasks.badge', 'Tasks'), icon: ListTodo, path: `/mobile/events/${slug}/tasks`, color: theme.accent } : null,
    !isCompleted ? { label: t('management:events.quick.photobooth', 'Photobooth'), icon: Camera, path: `/mobile/events/${slug}/photobooth`, color: '#8B5CF6' } : null,
  ].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));

  const operationsItems = [
    !isCompleted ? { label: t('management:invites.badge', 'QR Codes'), icon: QrCode, path: `/mobile/events/${slug}/qr`, color: '#10B981' } : null,
    { label: t('management:events.quick.guests', 'Guests'), icon: Users, path: `/mobile/events/${slug}/members`, color: theme.text },
    !isCompleted ? { label: t('management:events.quick.guestMessages', 'Messages'), icon: Megaphone, path: `/mobile/events/${slug}/guest-notifications`, color: theme.text } : null,
    !isCompleted ? { label: t('events.branding.titleShort', 'Branding'), icon: Layout, path: `/mobile/events/${slug}/branding`, color: theme.text } : null,
  ].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));

  const adminItems = [
    { label: t('management:mobileDashboard.shortcutAnalytics', 'Analytics'), icon: TrendingUp, path: `/mobile/events/${slug}/analytics` },
    !isCompleted ? { label: t('events.recap.exportTitleShort', 'Exports'), icon: Download, path: `/mobile/exports` } : null,
    { label: t('management:mobileProfile.settings', 'Settings'), icon: Settings, path: `/mobile/events/${slug}/edit` },
  ].filter((item): item is { label: string; icon: any; path: string; color?: string } => Boolean(item));

  const sections = [
    {
      title: t('management:branding.badge', 'Experience'), 
      items: experienceItems,
    },
    {
      title: t('management:workspace.hero.badge', 'Operations'), 
      items: operationsItems,
    },
    {
       title: t('management:settings.hero.badge', 'Admin'),
       items: adminItems,
    }
  ].filter((section) => section.items.length > 0);

  return (
    <YStack space="$4">
      {sections.map((section) => (
        <YStack key={section.title} space="$2">
          <Text fontSize="$xs" fontWeight="700" color={theme.muted} textTransform="uppercase" letterSpacing={1}>
            {section.title}
          </Text>
          <XStack flexWrap="wrap" gap="$2.5">
             {section.items.map((item) => (
                <Pressable 
                   key={item.label} 
                   onPress={() => navigate(adminPath(item.path))}
                   style={{ width: '48%', flexGrow: 1 }}
                >
                   <YStack 
                      backgroundColor={theme.surface} 
                      borderRadius={14} 
                      padding="$3" 
                      space="$2.5" 
                      borderWidth={1}
                      borderColor={theme.border}
                      height={90}
                      justifyContent="space-between"
                   >
                      <XStack justifyContent="space-between" alignItems="flex-start">
                         <YStack 
                            width={32} height={32} 
                            borderRadius={10} 
                            backgroundColor={item.color ? withAlpha(item.color, 0.1) : theme.surfaceMuted} 
                            alignItems="center" justifyContent="center"
                         >
                            <item.icon size={18} color={item.color || theme.textStrong} />
                         </YStack>
                      </XStack>
                      <Text fontSize="$sm" fontWeight="700" color={theme.textStrong}>
                         {item.label}
                      </Text>
                   </YStack>
                </Pressable>
             ))}
          </XStack>
        </YStack>
      ))}
    </YStack>
  );
}

function RecentPhotosSection({ photos, navigate, slug }: { photos: TenantPhoto[], navigate: any, slug: string }) {
  const theme = useAdminTheme();
  const { t } = useTranslation('management');
  
  if (!photos.length) return null;

  return (
    <YStack space="$2">
       <XStack alignItems="center" justifyContent="space-between">
         <Text fontSize="$xs" fontWeight="700" color={theme.muted} textTransform="uppercase" letterSpacing={1}>
           {t('photos.recentTitle', 'Latest Uploads')}
         </Text>
         <Pressable onPress={() => navigate(adminPath(`/mobile/events/${slug}/control-room`))}>
           <Text fontSize="$xs" color={theme.primary} fontWeight="600">{t('common.all', 'See all')}</Text>
         </Pressable>
       </XStack>
       
       <XStack space="$2" overflow="scroll" paddingVertical="$1">
          {photos.map((photo) => (
             <Pressable key={photo.id} onPress={() => navigate(adminPath(`/mobile/events/${slug}/control-room`))}>
               <YStack 
                 width={80} 
                 height={80} 
                 borderRadius={12} 
                 overflow="hidden" 
                 backgroundColor={theme.surfaceMuted}
                 borderWidth={1}
                 borderColor={theme.border}
               >
                 {photo.thumbnail_url ? (
                   <Image 
                     source={{ uri: photo.thumbnail_url }} 
                     width={80} 
                     height={80} 
                     resizeMode="cover" 
                   />
                 ) : (
                   <YStack flex={1} alignItems="center" justifyContent="center">
                     <ImageIcon size={20} color={theme.muted} />
                   </YStack>
                 )}
               </YStack>
             </Pressable>
          ))}
       </XStack>
    </YStack>
  );
}

function AlertsSection({ event, stats, t }: any) {
   const theme = useAdminTheme();
   const limitWarnings = buildLimitWarnings(event?.limits ?? null, translateLimits(t)); 
   
   if (!limitWarnings.length) return null;

   return (
      <YStack space="$2">
         {limitWarnings.map((w: any, idx: number) => {
            const isDanger = w.tone === 'danger';
            const bg = isDanger ? theme.dangerBg : theme.warningBg;
            const border = isDanger ? theme.dangerText : theme.warningBorder;
            const text = isDanger ? theme.dangerText : theme.warningText;
            const Icon = isDanger ? AlertCircle : Bell;

            return (
            <XStack 
               key={idx} 
               backgroundColor={bg} 
               padding="$3" 
               borderRadius={12} 
               borderWidth={1} 
               borderColor={border}
               alignItems="center"
               space="$2"
            >
               <Icon size={16} color={text} />
               <Text fontSize="$sm" color={text} fontWeight="600">
                  {w.message}
               </Text>
            </XStack>
            );
         })}
      </YStack>
   );
}

function EmptyState({ canManage, onCreate }: any) {
   const theme = useAdminTheme();
   const { t } = useTranslation(['management', 'mobile']);
   return (
      <YStack flex={1} alignItems="center" justifyContent="center" space="$4">
         <Sparkles size={48} color={theme.primary} />
         <Text fontSize="$lg" fontWeight="800" color={theme.textStrong} textAlign="center">
            {t('mobile:header.appName', 'Event Admin')}
         </Text>
         <Text fontSize="$sm" color={theme.muted} textAlign="center">
            {t('mobile:header.noEventsBody', 'Create your first event.')}
         </Text>
         {canManage && <ModernButton label={t('management:events.list.actions.create', 'Create Event')} onPress={onCreate} />}
      </YStack>
   );
}
