import { useState, useMemo } from 'react';
import {
  View,
  Text,
  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`;
}

type Props = {
  domains: CustomDomain[];
  tier: Tier;
  kind: 'web' | 'mail';
  onSubmit?: (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, kind, onSubmit, onUpgradePro }: Props) {
  const { t } = useTranslation();
  const colors = useColors();

  const visible = useMemo(() => {
    return domains
      .filter((d) => {
        if (d.status === 'approved') return false;
        if (kind === 'mail') {
          return d.type === 'mail_domain';
        }
        return d.type === 'web' || !d.type;
      })
      .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, kind]);

  return (
    <View style={{ gap: 12 }}>
      {/* 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={kind === 'mail' ? 'mail-outline' : 'globe-outline'}
            size={28}
            color={colors.textMuted}
          />
          <Text
            style={{
              fontSize: 13,
              fontFamily: 'Nunito_400Regular',
              color: colors.textMuted,
              marginTop: 8,
              textAlign: 'center',
            }}
          >
            {kind === 'mail' ? t('blocker.empty_mail') : t('blocker.empty_web')}
          </Text>
        </View>
      ) : (
        <DomainTilesGrid
          domains={visible}
          tier={tier}
          onSubmit={onSubmit}
        />
      )}
    </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 kollabiert 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';

  const statusColor = (() => {
    switch (domain.status) {
      case 'submitted':
        return '#f59e0b';
      case 'rejected':
        return '#FF3B30';
      default:
        return '#007AFF';
    }
  })();

  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');
    }
  })();

  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 isMailDisplayName = domain.type === 'mail_display_name';
  const isFreeAndUsed = tier.plan === 'free' && domain.status !== 'active';
  const showSubmit = tier.canSubmit && domain.status === 'active' && !isMailDisplayName;
  const showResubmit = tier.canSubmit && domain.status === 'rejected' && !isMailDisplayName;
  const showInPruefungBtn = domain.status === 'submitted';

  return (
    <View
      style={{
        backgroundColor: colors.bg,
        borderWidth: 1,
        borderColor: colors.border,
        borderRadius: 14,
        padding: 8,
        minHeight: 130,
        opacity: isFreeAndUsed ? 0.55 : 1,
        gap: 6,
      }}
    >
      {/* Top-Row: Zeit links · Badge rechts */}
      <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: Icon + Domain-Name */}
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', gap: 4, paddingVertical: 8 }}>
        {domain.type === 'mail_domain' || domain.type === 'mail_display_name' ? (
          <View
            style={{
              width: 26,
              height: 26,
              borderRadius: 5,
              backgroundColor: '#dbeafe',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Ionicons name="mail-outline" size={14} color="#2563eb" />
          </View>
        ) : !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 (28px), Inhalt je nach Status. */}
      <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 && (
          <TouchableOpacity
            onPress={openConfirm}
            disabled={submitting}
            activeOpacity={0.75}
            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>
            )}
          </TouchableOpacity>
        )}
        {showResubmit && (
          <TouchableOpacity
            onPress={openConfirm}
            disabled={submitting}
            activeOpacity={0.75}
            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>
            )}
          </TouchableOpacity>
        )}
      </View>

      <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)}
      />

      <SuccessAlert
        visible={successVisible}
        title={successContent.title}
        message={successContent.message}
        onClose={() => setSuccessVisible(false)}
      />
    </View>
  );
}
