import { useTheme } from '@/components/ThemeContext';
import CategorySelection from '@/components/ui/IndustrySelection';
import { XIcon } from 'lucide-react-native';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FlatList, StyleSheet, Text, ToastAndroid, TouchableOpacity, View } from 'react-native';

type StepProps = {
  formData: any;
  updateForm: (key: string, value: any) => void;
};

const StepTwo = forwardRef(({ formData, updateForm }: StepProps, ref) => {
  const [selectedCategories, setSelectedCategories] = useState<any[]>(formData.category || []);
  const [error, setError] = useState<string | null>(null);
  const { isDark } = useTheme();
  const { t } = useTranslation();

  const theme = {
    text: isDark ? '#f8fafc' : '#0f172a',
    tabBg: isDark ? '#1e293b' : '#f1f5f9',
    tabText: isDark ? '#ffffff' : '#1e293b',
    deleteBg: isDark ? '#394e73' : '#cbd5e1',
    deleteIcon: isDark ? '#f8fafc' : '#475569',
    error: '#ef4444',
    shadow: isDark ? '#000' : '#64748b',
  };

  // FormData-ni yangilash
  useEffect(() => {
    updateForm('category', selectedCategories);
    if (selectedCategories.length > 0) setError(null);
  }, [selectedCategories]);

  // Validatsiya
  const validate = () => {
    if (selectedCategories.length === 0) {
      setError('Iltimos, kompaniyalarni tanlang');
      ToastAndroid.show(t('Iltimos, kompaniyalarni tanlang'), ToastAndroid.TOP);
      return false;
    }
    return true;
  };

  useImperativeHandle(ref, () => ({
    validate,
  }));

  // O'chirish funksiyasi
  const removeCategory = (id: string | number) => {
    setSelectedCategories((prev) => prev.filter((c) => c.id !== id));
  };

  // SearchTabs uchun render funksiyasi
  const renderTab = ({ item }: { item: any }) => (
    <View style={[styles.tabWrapper, { backgroundColor: theme.tabBg, shadowColor: theme.shadow }]}>
      <Text
        style={[styles.tabText, { color: theme.tabText }]}
        numberOfLines={1}
        ellipsizeMode="tail"
      >
        {item.name}
      </Text>
      <TouchableOpacity
        onPress={() => removeCategory(item.id)}
        style={[styles.deleteTab, { backgroundColor: theme.deleteBg }]}
      >
        <XIcon size={15} color={theme.deleteIcon} />
      </TouchableOpacity>
    </View>
  );

  return (
    <View style={[styles.container]}>
      {/* Tanlangan kategoriya tablari */}
      {selectedCategories.length > 0 && (
        <>
          <Text style={[styles.label, { color: theme.text }]}>{t('Tanlangan sohalar')}:</Text>
          <FlatList
            data={selectedCategories}
            renderItem={renderTab}
            keyExtractor={(item) => item.id.toString()}
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.tabsContainer}
            ItemSeparatorComponent={() => <View style={{ width: 8 }} />}
          />
        </>
      )}

      {/* Kategoriya tanlash */}
      <Text style={[styles.label, { color: theme.text }]}>{t("Sohalar ro'yxati")}:</Text>
      <CategorySelection
        selectedCategories={selectedCategories}
        setSelectedCategories={setSelectedCategories}
      />
    </View>
  );
});

export default StepTwo;

const styles = StyleSheet.create({
  container: { flexGrow: 1 },
  label: {
    fontSize: 16,
    marginBottom: 5,
    fontWeight: '600',
  },
  error: {
    marginTop: 10,
    fontWeight: '600',
    fontSize: 14,
  },
  tabsContainer: {
    marginBottom: 16,
    paddingVertical: 4,
  },
  tabWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 8,
    paddingHorizontal: 12,
    borderRadius: 20,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 3,
    elevation: 3,
  },
  tabText: {
    fontSize: 14,
    fontWeight: '600',
    marginRight: 6,
    maxWidth: 200,
    flexShrink: 1,
  },
  deleteTab: {
    padding: 4,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
