import { useState, useMemo } from 'react';
import {
  View,
  Text,
  Pressable,
  TouchableOpacity,
  Image,
  ActivityIndicator,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { SuccessAlert } from '../SuccessAlert';
import { ConfirmAlert } from '../ConfirmAlert';
import type { CustomDomain, Tier } from '../../hooks/useCustomDomains';
import { useColors } from '../../lib/theme';

// ─── Helpers ─────────────────────────────────────────────────────────────

function timeAgo(input?: string | Date): string {
  if (!input) return '';
  const date = typeof input === 'string' ? new Date(input) : input;
  const diffMs = Date.now() - date.getTime();
  const minutes = Math.floor(diffMs / 60_000);
  if (minutes < 1) return 'jetzt';
  if (minutes < 60) return `${minutes}m`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours}h`;
  const days = Math.floor(hours / 24);
  if (days < 7) return `${days}d`;
  const weeks = Math.floor(days / 7);
  if (weeks < 5) return `${weeks}w`;
  const months = Math.floor(days / 30);
  return `${months}mo`;
}

function timeSinceSubmit(input?: string | Date): string {
  if (!input) return '';
  const date = typeof input === 'string' ? new Date(input) : input;
  const diffMs = Date.now() - date.getTime();
  const hours = Math.floor(diffMs / 3_600_000);
  if (hours < 1) {
    const minutes = Math.max(1, Math.floor(diffMs / 60_000));
    return `${minutes} min`;
  }
  if (hours < 24) return `${hours} Std`;
  const days = Math.floor(hours / 24);
  return `${days} Tag${days === 1 ? '' : 'e'}`;
}

type Props = {
  domains: CustomDomain[];
  tier: Tier;
  onAdd?: () => void;
  onSubmit?: (id: string) => Promise<{ ok: boolean }>;
  onRemove?: (id: string) => Promise<{ ok: boolean }>;
  onUpgradePro?: () => void;
};

// Sort-Reihenfolge: User sieht zuerst was Aufmerksamkeit braucht.
//  submitted (in Prüfung)  > rejected (kann erneut) > active (settled OK)
const STATUS_PRIORITY: Record<string, number> = {
  submitted: 0,
  rejected: 1,
  active: 2,
  approved: 99,
};

export function DomainGrid({ domains, tier, onAdd, onSubmit, onUpgradePro }: Props) {
  const { t } = useTranslation();
  const colors = useColors();
  // Slot-relevante Domains (alles außer approved). Sortiert nach Status-Priority,
  // innerhalb gleicher Priority dann newest-first by addedAt.
  const visible = useMemo(() => {
    return domains
      .filter((d) => d.status !== 'approved')
      .slice()
      .sort((a, b) => {
        const pa = STATUS_PRIORITY[a.status] ?? 99;
        const pb = STATUS_PRIORITY[b.status] ?? 99;
        if (pa !== pb) return pa - pb;
        const ta = a.addedAt ? new Date(a.addedAt).getTime() : 0;
        const tb = b.addedAt ? new Date(b.addedAt).getTime() : 0;
        return tb - ta;
      });
  }, [domains]);

  return (
    <View style={{ gap: 12 }}>
      {/* Header: Section-Title + Slot-Counter + Add-Button (inline, neben SlotPill) */}
      <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
        <Text style={{ fontSize: 14, fontFamily: 'Nunito_700Bold', color: colors.text }}>
          {t('blocker.domain_section_title')}
        </Text>
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
          <SlotPill tier={tier} />
          {onAdd && (
            <Pressable
              onPress={tier.atLimit ? undefined : onAdd}
              accessibilityLabel={t('blocker.domain_add_a11y')}
              accessibilityState={{ disabled: tier.atLimit }}
              disabled={tier.atLimit}
              hitSlop={8}
            >
              <View
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: 16,
                  // atLimit → grau + 50% opacity (deutlich visuell disabled)
                  backgroundColor: tier.atLimit ? '#a3a3a3' : '#007AFF',
                  opacity: tier.atLimit ? 0.5 : 1,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Ionicons name="add" size={22} color="#fff" />
              </View>
            </Pressable>
          )}
        </View>
      </View>

      {/* Progress-Bar — 3-stufige Color-Schwelle: <60% grün, 60-90% orange, >=90% rot */}
      {(() => {
        const pct = (tier.usedSlots / tier.domainLimit) * 100;
        const barColor = pct >= 90 ? '#dc2626' : pct >= 60 ? '#f59e0b' : '#16a34a';
        return (
          <View style={{ height: 4, borderRadius: 2, backgroundColor: colors.surfaceElevated, overflow: 'hidden' }}>
            <View
              style={{
                height: '100%',
                width: `${Math.min(100, pct)}%`,
                backgroundColor: barColor,
              }}
            />
          </View>
        );
      })()}

      {/* Limit-Reached Upsell (nur Free) */}
      {tier.atLimit && tier.plan === 'free' && (
        <TouchableOpacity
          onPress={onUpgradePro}
          activeOpacity={0.85}
        >
          <View style={{
            backgroundColor: '#eff6ff',
            borderWidth: 1,
            borderColor: '#bfdbfe',
            borderRadius: 12,
            padding: 12,
            flexDirection: 'row',
            alignItems: 'center',
            gap: 10,
          }}>
            <Ionicons name="lock-closed" size={18} color="#2563eb" />
            <View style={{ flex: 1 }}>
              <Text style={{ fontSize: 13, fontFamily: 'Nunito_600SemiBold', color: '#1e3a8a' }}>
                {t('blocker.domain_limit_title')}
              </Text>
              <Text style={{ fontSize: 11, fontFamily: 'Nunito_400Regular', color: '#3b82f6' }}>
                {t('blocker.domain_limit_desc')}
              </Text>
            </View>
          </View>
        </TouchableOpacity>
      )}

      {/* Empty State */}
      {visible.length === 0 ? (
        <View
          style={{
            paddingVertical: 32,
            paddingHorizontal: 16,
            borderRadius: 14,
            borderWidth: 1,
            borderStyle: 'dashed',
            borderColor: colors.border,
            alignItems: 'center',
          }}
        >
          <Ionicons name="globe-outline" size={28} color={colors.textMuted} />
          <Text
            style={{
              fontSize: 13,
              fontFamily: 'Nunito_400Regular',
              color: colors.textMuted,
              marginTop: 8,
              textAlign: 'center',
            }}
          >
            {t('blocker.domain_empty')}
          </Text>
        </View>
      ) : (
        <DomainTilesGrid
          domains={visible}
          tier={tier}
          onSubmit={onSubmit}
        />
      )}
    </View>
  );
}

// ─── SlotPill ─────────────────────────────────────────────────────────────

function SlotPill({ tier }: { tier: Tier }) {
  const colors = useColors();
  const bg = tier.atLimit ? '#fee2e2' : colors.surfaceElevated;
  const fg = tier.atLimit ? '#dc2626' : colors.textMuted;
  return (
    <View
      style={{
        paddingHorizontal: 8,
        paddingVertical: 3,
        borderRadius: 999,
        backgroundColor: bg,
      }}
    >
      <Text style={{ fontSize: 11, fontFamily: 'Nunito_600SemiBold', color: fg }}>
        {tier.usedSlots}/{tier.domainLimit}
      </Text>
    </View>
  );
}

// ─── Tiles ────────────────────────────────────────────────────────────────

function DomainTilesGrid({
  domains,
  tier,
  onSubmit,
}: {
  domains: CustomDomain[];
  tier: Tier;
  onSubmit?: (id: string) => Promise<{ ok: boolean }>;
}) {
  // 3-Spalten-Grid via flex-wrap. Parent ScrollView (in blocker.tsx) handles scroll —
  // KEIN nested ScrollView hier, sonst collabiert der Layout-Pass weil ScrollView
  // inner-content-view keine definierte Width für %-basierte Tile-Widths hat.
  return (
    <View style={{ flexDirection: 'row', flexWrap: 'wrap', rowGap: 14 }}>
      {domains.map((d) => (
        <View key={d.id} style={{ width: '33.333%', paddingHorizontal: 4 }}>
          <DomainTile domain={d} tier={tier} onSubmit={onSubmit} />
        </View>
      ))}
    </View>
  );
}

function DomainTile({
  domain,
  tier,
  onSubmit,
}: {
  domain: CustomDomain;
  tier: Tier;
  onSubmit?: (id: string) => Promise<{ ok: boolean }>;
}) {
  const { t } = useTranslation();
  const colors = useColors();
  const [submitting, setSubmitting] = useState(false);
  const [imgError, setImgError] = useState(false);
  const [successVisible, setSuccessVisible] = useState(false);
  const [successContent, setSuccessContent] = useState<{ title: string; message: string }>({
    title: '',
    message: '',
  });
  const [confirmVisible, setConfirmVisible] = useState(false);
  const stripped = domain.domain.replace(/^www\./, '');

  const isLegend = tier.plan === 'legend';

  // statusColor wird auf Badge + Button angewendet.
  // iOS-native: blue (active), orange (submitted), red (rejected).
  const statusColor = (() => {
    switch (domain.status) {
      case 'submitted':
        return '#f59e0b'; // orange (Voting/Prüfung)
      case 'rejected':
        return '#FF3B30'; // iOS-red
      default:
        return '#007AFF'; // iOS-blue (active, "freigeben"-CTA)
    }
  })();

  // Time-Color: nur Status die Aufmerksamkeit brauchen (submitted/rejected) sind farbig.
  // Active = neutral gray (settled state, kein Alarm-Indikator nötig).
  const timeColor = domain.status === 'active' ? '#a3a3a3' : statusColor;

  const badgeLabel = (() => {
    switch (domain.status) {
      case 'submitted':
        return isLegend ? t('blocker.domain_badge_pruefung') : t('blocker.domain_badge_voting');
      case 'rejected':
        return t('blocker.domain_badge_rejected');
      default:
        return t('blocker.domain_badge_active');
    }
  })();

  // Tier-aware Confirm-Dialog vor Freigabe — Pro geht zu Community-Voting,
  // Legend direkt zum ReBreak-Team. Animiertes Modal statt nativem Alert.
  const isResubmit = domain.status === 'rejected';
  const confirmTitle = isLegend
    ? isResubmit
      ? t('blocker.domain_confirm_legend_resubmit')
      : t('blocker.domain_confirm_legend_first')
    : isResubmit
      ? t('blocker.domain_confirm_community_resubmit')
      : t('blocker.domain_confirm_community_first');
  const confirmMessage = isLegend
    ? t('blocker.domain_confirm_legend_message', { domain: stripped })
    : t('blocker.domain_confirm_community_message', { domain: stripped });

  function openConfirm() {
    if (!onSubmit) return;
    setConfirmVisible(true);
  }

  async function handleConfirm() {
    setConfirmVisible(false);
    if (!onSubmit) return;

    setSubmitting(true);
    try {
      const result = await onSubmit(domain.id);
      if (result.ok) {
        setSuccessContent({
          title: isLegend ? t('blocker.domain_success_legend_title') : t('blocker.domain_success_community_title'),
          message: isLegend
            ? t('blocker.domain_success_legend_message')
            : t('blocker.domain_success_community_message'),
        });
        setSuccessVisible(true);
      }
    } finally {
      setSubmitting(false);
    }
  }

  const isFreeAndUsed = tier.plan === 'free' && domain.status !== 'active';
  const showSubmit = tier.canSubmit && domain.status === 'active';
  const showResubmit = tier.canSubmit && domain.status === 'rejected';
  const showInPruefungBtn = domain.status === 'submitted';

  return (
    <View
      style={{
        backgroundColor: colors.bg,
        borderWidth: 1,
        borderColor: colors.border,
        borderRadius: 14,
        padding: 8,
        // KEIN aspectRatio:1 mehr — der hat den Button auf 0 Höhe gepresst.
        // minHeight statt fixer aspect-ratio: Tile darf wachsen wenn Button da ist,
        // bleibt aber konsistent groß für visuelle Stabilität.
        minHeight: 130,
        opacity: isFreeAndUsed ? 0.55 : 1,
        gap: 6,
      }}
    >
      {/* Top-Row: Zeit links · Badge rechts — beide in Status-Color (matcht Bottom-Button). */}
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 4,
        }}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
          <Ionicons name="time-outline" size={9} color={timeColor} />
          <Text style={{ fontSize: 9, fontFamily: 'Nunito_600SemiBold', color: timeColor }}>
            {timeAgo(domain.addedAt)}
          </Text>
        </View>
        <View
          style={{
            paddingHorizontal: 5,
            paddingVertical: 1,
            borderRadius: 999,
            backgroundColor: statusColor,
          }}
        >
          <Text style={{ fontSize: 8, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
            {badgeLabel}
          </Text>
        </View>
      </View>

      {/* Mitte: Favicon + Domain-Name (zentriert, flex-1) */}
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 4, paddingVertical: 8 }}>
        {!imgError ? (
          <Image
            source={{ uri: `https://www.google.com/s2/favicons?domain=${stripped}&sz=128` }}
            style={{ width: 26, height: 26, borderRadius: 5 }}
            onError={() => setImgError(true)}
          />
        ) : (
          <View
            style={{
              width: 26,
              height: 26,
              borderRadius: 5,
              backgroundColor: '#525252',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Text style={{ fontSize: 9, fontFamily: 'Nunito_700Bold', color: '#fff' }}>
              {stripped.slice(0, 2).toUpperCase()}
            </Text>
          </View>
        )}
        <Text
          numberOfLines={1}
          style={{
            fontSize: 10,
            fontFamily: 'Nunito_600SemiBold',
            color: colors.text,
            textAlign: 'center',
            width: '100%',
          }}
        >
          {stripped}
        </Text>
      </View>

      {/* Bottom-Slot: ALWAYS rendered Container (32px), Inhalt je nach Status.
       *  Garantiert konsistente Tile-Höhe + sichtbaren Button. */}
      <View style={{ height: 28 }}>
        {showInPruefungBtn && (
          <View
            style={{
              flex: 1,
              backgroundColor: '#f59e0b',
              borderRadius: 6,
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Text style={{ fontSize: 10, fontFamily: 'Nunito_600SemiBold', color: '#fff' }}>
              {isLegend ? t('blocker.domain_btn_rebreak_prueft') : t('blocker.domain_btn_in_abstimmung')}
            </Text>
          </View>
        )}
        {showSubmit && (
          <Pressable
            onPress={openConfirm}
            disabled={submitting}
            style={{
              flex: 1,
              borderRadius: 6,
              backgroundColor: 'transparent',
              borderWidth: 1,
              borderColor: '#007AFF',
              alignItems: 'center',
              justifyContent: 'center',
              opacity: submitting ? 0.5 : 1,
            }}
          >
            {submitting ? (
              <ActivityIndicator size="small" color="#007AFF" />
            ) : (
              <Text style={{ fontSize: 10, fontFamily: 'Nunito_600SemiBold', color: '#007AFF' }}>
                {t('blocker.domain_btn_freigeben')}
              </Text>
            )}
          </Pressable>
        )}
        {showResubmit && (
          <Pressable
            onPress={openConfirm}
            disabled={submitting}
            style={{
              flex: 1,
              borderRadius: 6,
              backgroundColor: 'transparent',
              borderWidth: 1,
              borderColor: '#FF3B30',
              alignItems: 'center',
              justifyContent: 'center',
              opacity: submitting ? 0.5 : 1,
            }}
          >
            {submitting ? (
              <ActivityIndicator size="small" color="#FF3B30" />
            ) : (
              <Text style={{ fontSize: 10, fontFamily: 'Nunito_600SemiBold', color: '#FF3B30' }}>
                {t('blocker.domain_btn_erneut')}
              </Text>
            )}
          </Pressable>
        )}
      </View>

      {/* Confirm-Modal vor Submit (statt nativer Alert.alert — selber animation-Style wie SuccessAlert) */}
      <ConfirmAlert
        visible={confirmVisible}
        title={confirmTitle}
        message={confirmMessage}
        confirmLabel={t('blocker.domain_btn_freigeben')}
        icon={isLegend ? 'shield-checkmark' : 'people'}
        iconColor="#f59e0b"
        onConfirm={handleConfirm}
        onCancel={() => setConfirmVisible(false)}
      />

      {/* Success-Alert mit animiertem Check-Icon nach erfolgreichem Submit */}
      <SuccessAlert
        visible={successVisible}
        title={successContent.title}
        message={successContent.message}
        onClose={() => setSuccessVisible(false)}
      />
    </View>
  );
}
