// SearchResultsScreen.tsx
import { useTheme } from '@/components/ThemeContext';
import {
  Award,
  Building2,
  Calendar,
  ChevronLeft,
  DollarSign,
  Info,
  Mail,
  MapPin,
  Phone,
  User,
} from 'lucide-react-native';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, Image, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type TabType = 'entity' | 'entrepreneur' | 'trademark';

interface SearchResult {
  entity: any;
  entrepreneur: any;
  trademark: any;
}

interface SearchResultsScreenProps {
  searchData: SearchResult;
  onBack: () => void;
}

export default function SearchResultsScreen({ searchData, onBack }: SearchResultsScreenProps) {
  const { isDark } = useTheme();
  const { t } = useTranslation();
  const [activeTab, setActiveTab] = useState<TabType>('entity');

  const tabs = [
    {
      key: 'entity' as TabType,
      label: 'Korxonalar',
      icon: Building2,
      count:
        searchData.entity.name.total +
        searchData.entity.director.total +
        searchData.entity.founder.total,
    },
    {
      key: 'entrepreneur' as TabType,
      label: 'Tadbirkorlar',
      icon: User,
      count: searchData.entrepreneur.total,
    },
    {
      key: 'trademark' as TabType,
      label: 'Tovar belgilari',
      icon: Award,
      count: searchData.trademark.total,
    },
  ];

  const renderTabs = () => (
    <View style={styles.tabsContainer}>
      {tabs.map((tab) => {
        const Icon = tab.icon;
        const isActive = activeTab === tab.key;
        return (
          <TouchableOpacity
            key={tab.key}
            style={[
              styles.tab,
              isActive && styles.activeTab,
              {
                backgroundColor: isActive
                  ? isDark
                    ? '#3b82f6'
                    : '#3b82f6'
                  : isDark
                    ? '#1e293b'
                    : '#f1f5f9',
              },
            ]}
            onPress={() => setActiveTab(tab.key)}
          >
            <Icon size={18} color={isActive ? '#ffffff' : isDark ? '#94a3b8' : '#64748b'} />
            <Text
              style={[
                styles.tabText,
                { color: isActive ? '#ffffff' : isDark ? '#94a3b8' : '#64748b' },
              ]}
            >
              {tab.label}
            </Text>
            {tab.count > 0 && (
              <View style={[styles.badge, { backgroundColor: isActive ? '#60a5fa' : '#3b82f6' }]}>
                <Text style={styles.badgeText}>{tab.count > 9999 ? '9999+' : tab.count}</Text>
              </View>
            )}
          </TouchableOpacity>
        );
      })}
    </View>
  );

  const renderEntityCard = (item: any, variant: string) => (
    <View
      style={[
        styles.card,
        {
          backgroundColor: isDark ? '#1e293b' : '#ffffff',
          borderColor: isDark ? '#334155' : '#e2e8f0',
        },
      ]}
    >
      {/* Header */}
      <View style={styles.cardHeader}>
        <View
          style={[
            styles.statusBadge,
            { backgroundColor: item.activity_state === 1 ? '#22c55e' : '#ef4444' },
          ]}
        >
          <Text style={styles.statusText}>{item.activity_state === 1 ? 'Faol' : 'Faol emas'}</Text>
        </View>
        {variant && (
          <View style={[styles.variantBadge, { backgroundColor: isDark ? '#334155' : '#f1f5f9' }]}>
            <Text style={[styles.variantText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
              {variant === 'director' ? 'Direktor' : variant === 'founder' ? "Ta'sischi" : 'Nomi'}
            </Text>
          </View>
        )}
      </View>

      {/* Company Name */}
      <Text style={[styles.cardTitle, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>{item.name}</Text>

      {/* INN */}
      <View style={styles.infoRow}>
        <Info size={16} color={isDark ? '#94a3b8' : '#64748b'} />
        <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>INN:</Text>
        <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
          {item.inn}
        </Text>
      </View>

      {/* Director */}
      {item.director && (
        <View style={styles.infoRow}>
          <User size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Direktor:
          </Text>
          <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {item.director}
          </Text>
        </View>
      )}

      {/* Address */}
      {item.address && (
        <View style={styles.infoRow}>
          <MapPin size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>Manzil:</Text>
          <Text
            style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}
            numberOfLines={2}
          >
            {item.address}
          </Text>
        </View>
      )}

      {/* Registration Date */}
      {item.registration_date && (
        <View style={styles.infoRow}>
          <Calendar size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Ro'yxatga olingan:
          </Text>
          <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {new Date(item.registration_date).toLocaleDateString('uz-UZ')}
          </Text>
        </View>
      )}

      {/* Activity */}
      <View style={[styles.activityBox, { backgroundColor: isDark ? '#0f172a' : '#f8fafc' }]}>
        <Text style={[styles.activityCode, { color: isDark ? '#60a5fa' : '#3b82f6' }]}>
          {item.oked_code}
        </Text>
        <Text style={[styles.activityName, { color: isDark ? '#cbd5e1' : '#475569' }]}>
          {item.oked_name}
        </Text>
      </View>

      {/* Contact Info */}
      <View style={styles.contactRow}>
        {item.email && (
          <View style={styles.contactItem}>
            <Mail size={14} color={isDark ? '#94a3b8' : '#64748b'} />
            <Text style={[styles.contactText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
              {item.email}
            </Text>
          </View>
        )}
        {item.phones?.length > 0 && (
          <View style={styles.contactItem}>
            <Phone size={14} color={isDark ? '#94a3b8' : '#64748b'} />
            <Text style={[styles.contactText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
              {item.phones[0]}
            </Text>
          </View>
        )}
      </View>

      {/* Statutory Fund */}
      {item.statutory_fund && (
        <View style={styles.fundRow}>
          <DollarSign size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.fundLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Ustav fondi:
          </Text>
          <Text style={[styles.fundValue, { color: isDark ? '#22c55e' : '#16a34a' }]}>
            {parseFloat(item.statutory_fund).toLocaleString('uz-UZ')} so'm
          </Text>
        </View>
      )}
    </View>
  );

  const renderEntrepreneurCard = (item: any) => (
    <View
      style={[
        styles.card,
        {
          backgroundColor: isDark ? '#1e293b' : '#ffffff',
          borderColor: isDark ? '#334155' : '#e2e8f0',
        },
      ]}
    >
      <View style={styles.entrepreneurHeader}>
        <View style={[styles.avatarCircle, { backgroundColor: isDark ? '#334155' : '#e2e8f0' }]}>
          <User size={32} color={isDark ? '#94a3b8' : '#64748b'} />
        </View>
        <View style={{ flex: 1 }}>
          <Text style={[styles.entrepreneurName, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {item.entrepreneur}
          </Text>
          <Text style={[styles.pinfl, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            PINFL: {item.pinfl}
          </Text>
        </View>
      </View>

      {item.registration_date && (
        <View style={styles.infoRow}>
          <Calendar size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Ro'yxatga olingan:
          </Text>
          <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {new Date(item.registration_date).toLocaleDateString('uz-UZ')}
          </Text>
        </View>
      )}

      {item.email && (
        <View style={styles.contactItem}>
          <Mail size={14} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.contactText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            {item.email}
          </Text>
        </View>
      )}

      {item.phone && (
        <View style={styles.contactItem}>
          <Phone size={14} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.contactText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            {item.phone}
          </Text>
        </View>
      )}
    </View>
  );

  const renderTrademarkCard = (item: any) => (
    <View
      style={[
        styles.card,
        {
          backgroundColor: isDark ? '#1e293b' : '#ffffff',
          borderColor: isDark ? '#334155' : '#e2e8f0',
        },
      ]}
    >
      <View style={styles.trademarkHeader}>
        {item.logo && (
          <Image source={{ uri: item.logo }} style={styles.trademarkLogo} resizeMode="contain" />
        )}
        <View style={{ flex: 1 }}>
          <Text style={[styles.trademarkName, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {item.transliteration}
          </Text>
          <View
            style={[
              styles.statusBadge,
              {
                backgroundColor:
                  item.status_name === 'COMPLETED'
                    ? '#22c55e'
                    : item.status_name === 'WAITING'
                      ? '#f59e0b'
                      : '#ef4444',
                alignSelf: 'flex-start',
              },
            ]}
          >
            <Text style={styles.statusText}>{item.status_name}</Text>
          </View>
        </View>
      </View>

      <View style={styles.infoRow}>
        <User size={16} color={isDark ? '#94a3b8' : '#64748b'} />
        <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
          Ariza beruvchi:
        </Text>
        <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
          {item.applicant}
        </Text>
      </View>

      {item.registration_date && (
        <View style={styles.infoRow}>
          <Calendar size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Ro'yxatga olingan:
          </Text>
          <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {new Date(item.registration_date).toLocaleDateString('uz-UZ')}
          </Text>
        </View>
      )}

      {item.relevance_date && (
        <View style={styles.infoRow}>
          <Calendar size={16} color={isDark ? '#94a3b8' : '#64748b'} />
          <Text style={[styles.infoLabel, { color: isDark ? '#94a3b8' : '#64748b' }]}>
            Amal qilish muddati:
          </Text>
          <Text style={[styles.infoValue, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
            {new Date(item.relevance_date).toLocaleDateString('uz-UZ')}
          </Text>
        </View>
      )}
    </View>
  );

  const renderContent = () => {
    switch (activeTab) {
      case 'entity':
        const allEntities = [
          ...searchData.entity.name.rows.map((r: any) => ({ ...r, variant: 'name' })),
          ...searchData.entity.director.rows.map((r: any) => ({ ...r, variant: 'director' })),
          ...searchData.entity.founder.rows.map((r: any) => ({ ...r, variant: 'founder' })),
        ];

        return (
          <FlatList
            data={allEntities}
            keyExtractor={(item, index) => `entity-${item.id}-${index}`}
            renderItem={({ item }) => renderEntityCard(item, item.variant)}
            contentContainerStyle={styles.listContent}
            showsVerticalScrollIndicator={false}
            ListEmptyComponent={
              <View style={styles.emptyState}>
                <Building2 size={48} color={isDark ? '#475569' : '#94a3b8'} />
                <Text style={[styles.emptyText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
                  Korxonalar topilmadi
                </Text>
              </View>
            }
          />
        );

      case 'entrepreneur':
        return (
          <FlatList
            data={searchData.entrepreneur.rows}
            keyExtractor={(item) => `entrepreneur-${item.id}`}
            renderItem={({ item }) => renderEntrepreneurCard(item)}
            contentContainerStyle={styles.listContent}
            showsVerticalScrollIndicator={false}
            ListEmptyComponent={
              <View style={styles.emptyState}>
                <User size={48} color={isDark ? '#475569' : '#94a3b8'} />
                <Text style={[styles.emptyText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
                  Tadbirkorlar topilmadi
                </Text>
              </View>
            }
          />
        );

      case 'trademark':
        return (
          <FlatList
            data={searchData.trademark.rows}
            keyExtractor={(item) => `trademark-${item.id}`}
            renderItem={({ item }) => renderTrademarkCard(item)}
            contentContainerStyle={styles.listContent}
            showsVerticalScrollIndicator={false}
            ListEmptyComponent={
              <View style={styles.emptyState}>
                <Award size={48} color={isDark ? '#475569' : '#94a3b8'} />
                <Text style={[styles.emptyText, { color: isDark ? '#94a3b8' : '#64748b' }]}>
                  Tovar belgilari topilmadi
                </Text>
              </View>
            }
          />
        );
    }
  };

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: isDark ? '#0f172a' : '#f8fafc' }]}>
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity onPress={onBack} style={styles.backButton}>
          <ChevronLeft size={24} color={isDark ? '#f1f5f9' : '#0f172a'} />
        </TouchableOpacity>
        <Text style={[styles.headerTitle, { color: isDark ? '#f1f5f9' : '#0f172a' }]}>
          Qidiruv natijalari
        </Text>
        <View style={{ width: 24 }} />
      </View>

      {/* Tabs */}
      {renderTabs()}

      {/* Content */}
      {renderContent()}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '700',
  },
  tabsContainer: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    gap: 8,
    marginBottom: 16,
  },
  tab: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 12,
    paddingHorizontal: 8,
    borderRadius: 12,
    gap: 6,
  },
  activeTab: {
    shadowColor: '#3b82f6',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 3,
  },
  tabText: {
    fontSize: 13,
    fontWeight: '600',
  },
  badge: {
    paddingHorizontal: 6,
    paddingVertical: 2,
    borderRadius: 10,
    minWidth: 20,
    alignItems: 'center',
  },
  badgeText: {
    color: '#ffffff',
    fontSize: 10,
    fontWeight: '700',
  },
  listContent: {
    paddingHorizontal: 16,
    paddingBottom: 24,
  },
  card: {
    borderRadius: 16,
    padding: 16,
    marginBottom: 12,
    borderWidth: 1,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  cardHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  statusBadge: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 8,
  },
  statusText: {
    color: '#ffffff',
    fontSize: 12,
    fontWeight: '600',
  },
  variantBadge: {
    paddingHorizontal: 10,
    paddingVertical: 4,
    borderRadius: 8,
  },
  variantText: {
    fontSize: 12,
    fontWeight: '600',
  },
  cardTitle: {
    fontSize: 16,
    fontWeight: '700',
    marginBottom: 12,
  },
  infoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginBottom: 8,
  },
  infoLabel: {
    fontSize: 13,
    fontWeight: '500',
  },
  infoValue: {
    fontSize: 13,
    fontWeight: '600',
    flex: 1,
  },
  activityBox: {
    padding: 12,
    borderRadius: 8,
    marginTop: 8,
    marginBottom: 8,
  },
  activityCode: {
    fontSize: 14,
    fontWeight: '700',
    marginBottom: 4,
  },
  activityName: {
    fontSize: 12,
    lineHeight: 18,
  },
  contactRow: {
    gap: 8,
    marginTop: 8,
  },
  contactItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  contactText: {
    fontSize: 12,
  },
  fundRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    marginTop: 12,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: '#334155',
  },
  fundLabel: {
    fontSize: 13,
    fontWeight: '500',
  },
  fundValue: {
    fontSize: 14,
    fontWeight: '700',
  },
  entrepreneurHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    marginBottom: 16,
  },
  avatarCircle: {
    width: 56,
    height: 56,
    borderRadius: 28,
    alignItems: 'center',
    justifyContent: 'center',
  },
  entrepreneurName: {
    fontSize: 16,
    fontWeight: '700',
    marginBottom: 4,
  },
  pinfl: {
    fontSize: 12,
    fontWeight: '500',
  },
  trademarkHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    marginBottom: 16,
  },
  trademarkLogo: {
    width: 64,
    height: 64,
    borderRadius: 8,
  },
  trademarkName: {
    fontSize: 15,
    fontWeight: '700',
    marginBottom: 8,
  },
  emptyState: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 16,
    fontWeight: '500',
    marginTop: 12,
  },
});
