// template/src/components/Tile/index.tsx
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import {
  TileProps,
  AccountTileData,
  CreditTileData,
  ServiceTileData,
  ServiceGridData,
  PromotionalTileData
} from './types';
import { createTileStyles } from './styles';
import { useTheme } from '../../theme/ThemeProvider';
import { Icon } from '@components/Icon';
import { ThemedText } from '@components/ThemedText';
import { AmountDisplay } from '@components/AmountDisplay';

const Tile: React.FC<TileProps> = ({ type, data, style }) => {
  // Get theme from context
  const { theme, isLoading } = useTheme();

  // Show loading state while theme is loading
  if (isLoading || !theme) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#000' }}>
        <ThemedText style={{ color: 'white', fontSize: 16 }}>Loading theme...</ThemedText>
      </View>
    );
  }

  // Create theme-aware styles
  const styles = createTileStyles(theme);

  const renderTile = () => {
    // ... rest of your existing code stays the same
    switch (type) {
      case 'account':
        return renderAccountTile(data as AccountTileData);
      case 'creditCard':
        return renderCreditTile(data as CreditTileData);
      case 'service':
        return renderServiceTile(data as ServiceTileData);
      case 'serviceGrid':
        return renderServiceGrid(data as ServiceGridData);
      case 'promotional':
        return renderPromotionalTile(data as PromotionalTileData);
      default:
        return <ThemedText>Unknown tile type</ThemedText>;
    }
  };

  const renderAccountTile = (tileData: AccountTileData) => {
    if (tileData.variant === 'condensed') {
      return (
        <>
          <TouchableOpacity
            style={[
              styles.tile,
              styles.condensedAccountTile,
              tileData.promoMessage ? styles.tileWithPromo : null,
              style
            ]}
            onPress={tileData.onPress}
            activeOpacity={0.7}
          >
            <View style={styles.condensedAccountLeft}>
              <ThemedText variant="label" style={styles.condensedAccountTitle}>{tileData.title}</ThemedText>
              {tileData.subtitle && (
                <ThemedText variant="accountNumber" style={styles.condensedAccountSubtitle}>{tileData.subtitle}</ThemedText>
              )}
            </View>

            <View style={styles.condensedAccountRight}>
              <AmountDisplay
                amount={tileData.balance}
                size="large"
                color={tileData.balance < 0 ? "error" : undefined}
                textStyle={tileData.balance < 0 ? styles.negativeBalance : styles.positiveBalance}
              />
            </View>
          </TouchableOpacity>

          {/* Promo Message as separate element */}
          {tileData.promoMessage && (
            <TouchableOpacity
              style={styles.promoContainer}
              onPress={tileData.promoMessage.onPress}
              activeOpacity={0.7}
            >
              <ThemedText style={styles.promoText}>{tileData.promoMessage.text}</ThemedText>
              {tileData.promoMessage.showArrow && (
                <ThemedText style={styles.promoArrow}>→</ThemedText>
              )}
            </TouchableOpacity>
          )}
        </>
      );
    }

    // Detailed variant (existing layout)
    return (
      <>
        <TouchableOpacity
          style={[
            styles.tile,
            tileData.promoMessage ? styles.tileWithPromo : null,
            style
          ]}
          onPress={tileData.onPress}
          activeOpacity={0.7}
        >
          <View style={styles.tileHeader}>
            <View style={styles.tileHeaderLeft}>
              <ThemedText style={styles.tileTitle}>{tileData.title}</ThemedText>
              <ThemedText style={styles.tileSubtitle}>{tileData.subtitle}</ThemedText>
            </View>
            {tileData.showMenu && (
              <TouchableOpacity style={styles.menuButton}>
                <ThemedText style={styles.menuDots}>•••</ThemedText>
              </TouchableOpacity>
            )}
          </View>

          <ThemedText style={[styles.balance, tileData.balance < 0 ? styles.negativeBalance : styles.positiveBalance]}>
            {tileData.balance < 0 ? '-' : ''}£{Math.abs(tileData.balance).toFixed(2)}
          </ThemedText>

          {tileData.balanceLabel && (
            <ThemedText style={styles.balanceLabel}>{tileData.balanceLabel}</ThemedText>
          )}

          {tileData.additionalInfo && (
            <ThemedText style={styles.additionalInfo}>{tileData.additionalInfo}</ThemedText>
          )}

          {/* Actions inside the main tile */}
          {tileData.actions && tileData.actions.length > 0 && (
            <View style={styles.actionsContainer}>
              {tileData.actions.map((action, index) => (
                <TouchableOpacity
                  key={index}
                  style={styles.actionButton}
                  onPress={action.onPress}
                >
                  <ThemedText style={styles.actionButtonText}>{action.label}</ThemedText>
                </TouchableOpacity>
              ))}
            </View>
          )}
        </TouchableOpacity>

        {/* Promo Message as separate element */}
        {tileData.promoMessage && (
          <TouchableOpacity
            style={styles.promoContainer}
            onPress={tileData.promoMessage.onPress}
            activeOpacity={0.7}
          >
            <ThemedText style={styles.promoText}>{tileData.promoMessage.text}</ThemedText>
            {tileData.promoMessage.showArrow && (
              <ThemedText style={styles.promoArrow}>→</ThemedText>
            )}
          </TouchableOpacity>
        )}
      </>
    );
  };

  const renderCreditTile = (tileData: CreditTileData) => (
    <TouchableOpacity
      style={[styles.tile, style]}
      onPress={tileData.onPress}
      activeOpacity={0.7}
    >
      <View style={styles.tileHeader}>
        <View style={styles.tileHeaderLeft}>
          <ThemedText style={styles.tileTitle}>{tileData.title}</ThemedText>
          <ThemedText style={styles.tileSubtitle}>{tileData.subtitle}</ThemedText>
        </View>
        {tileData.showMenu && (
          <TouchableOpacity style={styles.menuButton}>
            <ThemedText style={styles.menuDots}>•••</ThemedText>
          </TouchableOpacity>
        )}
      </View>

      <ThemedText style={styles.balance}>£{tileData.balance.toLocaleString()}</ThemedText>

      {tileData.balanceLabel && (
        <ThemedText style={styles.balanceLabel}>{tileData.balanceLabel}</ThemedText>
      )}

      {tileData.availableCredit && (
        <ThemedText style={styles.additionalInfo}>
          Available credit: £{tileData.availableCredit.toLocaleString()}
        </ThemedText>
      )}

      {tileData.details && tileData.details.length > 0 && (
        <View style={styles.detailsContainer}>
          {tileData.details.map((detail, index) => (
            <View key={index} style={styles.detailRow}>
              <ThemedText style={styles.detailLabel}>{detail.label}</ThemedText>
              <ThemedText style={styles.detailValue}>{detail.value}</ThemedText>
            </View>
          ))}
        </View>
      )}

      {tileData.primaryAction && (
        <TouchableOpacity
          style={styles.primaryActionButton}
          onPress={tileData.primaryAction.onPress}
        >
          <ThemedText style={styles.primaryActionText}>{tileData.primaryAction.label}</ThemedText>
        </TouchableOpacity>
      )}
    </TouchableOpacity>
  );

  const renderServiceTile = (tileData: ServiceTileData) => (
    <TouchableOpacity
      style={[styles.tile, styles.serviceTile, style]}
      onPress={tileData.onPress}
      activeOpacity={0.7}
    >
      <View style={styles.serviceTileContent}>
        <View style={[styles.serviceIcon, { backgroundColor: tileData.icon.color }]}>
          <Icon name={tileData.icon.name} />
        </View>

        <View style={styles.serviceTextContainer}>
          <View style={styles.serviceTitleRow}>
            <ThemedText variant="labelSmall" style={styles.serviceTitle}>{tileData.title}</ThemedText>
            {tileData.badge && (
              <View style={[styles.badge, { backgroundColor: tileData.badge.color }]}>
                <ThemedText style={styles.badgeText}>{tileData.badge.text}</ThemedText>
              </View>
            )}
          </View>
          <ThemedText style={styles.serviceDescription}>{tileData.description}</ThemedText>
        </View>

        {tileData.showArrow && (
          <ThemedText style={styles.arrow}>→</ThemedText>
        )}
      </View>
    </TouchableOpacity>
  );

  const renderServiceGrid = (gridData: ServiceGridData) => (
    <View style={[styles.serviceGrid, style]}>
      {gridData.items.map((item) => (
        <TouchableOpacity
          key={item.id}
          style={styles.gridItem}
          onPress={item.onPress}
          activeOpacity={0.7}
        >
          <View style={[styles.gridIcon, { backgroundColor: item.icon.color }]}>
            <Icon name={item.icon.name} />
          </View>
          <ThemedText style={styles.gridTitle}>{item.title}</ThemedText>
          <ThemedText style={styles.gridDescription}>{item.description}</ThemedText>
        </TouchableOpacity>
      ))}
    </View>
  );

  const renderPromotionalTile = (tileData: PromotionalTileData) => (
    <TouchableOpacity
      style={[styles.tile, styles.promotionalTile, style]}
      onPress={tileData.onPress}
      activeOpacity={0.7}
    >
      <View style={styles.promotionalContent}>
        <View style={styles.promotionalText}>
          <ThemedText style={styles.promotionalTitle}>{tileData.title}</ThemedText>
          <ThemedText style={styles.promotionalDescription}>{tileData.description}</ThemedText>

          <TouchableOpacity
            style={styles.promotionalAction}
            onPress={tileData.action.onPress}
          >
            <ThemedText style={styles.promotionalActionText}>{tileData.action.label}</ThemedText>
            <ThemedText style={styles.promotionalArrow}>→</ThemedText>
          </TouchableOpacity>
        </View>

        {tileData.image && (
          <View style={[styles.promotionalImage, { backgroundColor: tileData.image.color }]}>
            <Icon name={tileData.image.name} />
          </View>
        )}
      </View>
    </TouchableOpacity>
  );

  return renderTile();
};

export default Tile;

// Re-export types for convenience
export * from './types';