import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import { useAppTheme } from '@theme';
import { ScreenHeader } from '@components';
import { WalletIcon, CheckCircleIcon, ClipboardIcon } from '@icons';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AppStackParamList } from '@navigation/navigationTypes';
import { RouteNames } from '@utils/constants';
import { BankAccount } from '@interfaces';
import { getStyles } from './bankDetailsScreen.styles';
import { formatDate, maskAccountNumber } from '@utils';
import { fetchBankAccounts } from '../addBankDetailsScreen';
import { useAppDispatch, useAppSelector } from '@store';

// ── Dummy data — replace with API data later ──────────────────────────────────
// const DUMMY_ACCOUNTS: BankAccount[] = [
//   {
//     id: '071e5d96-9e7f-4e57-a79c-593c2e2d0453',
//     ownerType: 'MERCHANT',
//     ownerId: 'b2b301a9-bc8f-4b22-b724-78279022dd85',
//     accountHolderName: 'sddsd',
//     bankName: 'sddsds',
//     accountNumber: 'ssdsds',
//     ifscCode: 'sdssd',
//     branchName: 'sdssdsd',
//     isDefault: true,
//     isVerified: false,
//     passbookImage:
//       '/bank-accounts/image/b2b301a9-bc8f-4b22-b724-78279022dd85-1784618982576.png',
//     createdAt: '2026-07-21T07:29:26.645Z',
//     updatedAt: '2026-07-21T07:29:42.582Z',
//   },
// ];
export const BankDetailsScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation =
    useNavigation<NativeStackNavigationProp<AppStackParamList>>();
  const dispatch = useAppDispatch();
  const { bankAccounts, isLoading, error } = useAppSelector(
    state => state.addBankDetails,
  );

  // Replace this state with Redux selector when wiring real API
  //   const [accounts] = useState<BankAccount[]>(bankAccounts);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    dispatch(fetchBankAccounts());
  }, []);

  const handleRefresh = () => {
    setRefreshing(true);
    dispatch(fetchBankAccounts())
      .unwrap()
      .then(() => setRefreshing(false))
      .catch(() => setRefreshing(false));
  };

  const handleAddAccount = () => {
    navigation.navigate(RouteNames.AddBankDetails);
  };

  return (
    <View style={styles.container}>
      <ScreenHeader
        title="Bank Details"
        showBack={true}
        onBack={() => navigation.goBack()}
      />

      <ScrollView
        contentContainerStyle={styles.scrollContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={handleRefresh}
            tintColor={colors.primary}
            colors={[colors.primary]}
          />
        }
      >
        {/* Summary Banner */}
        <View style={styles.summaryBanner}>
          <View style={styles.summaryIconCircle}>
            <WalletIcon size={22} color={colors.white} />
          </View>
          <View style={styles.summaryTextContainer}>
            <Text style={styles.summaryTitle}>Payout Accounts</Text>
            <Text style={styles.summarySubtitle}>
              Manage your bank accounts for receiving earnings
            </Text>
          </View>
        </View>

        {/* Empty State */}
        {bankAccounts?.length === 0 ? (
          <View style={styles.emptyContainer}>
            <View style={styles.emptyIconCircle}>
              <WalletIcon size={36} color={colors.primary} />
            </View>
            <Text style={styles.emptyTitle}>No Bank Accounts</Text>
            <Text style={styles.emptySubtitle}>
              Add your bank account to start receiving your delivery earnings
              directly.
            </Text>
          </View>
        ) : (
          <>
            {/* Section Header */}
            <View style={styles.sectionHeader}>
              <Text style={styles.sectionTitle}>Your Accounts</Text>
              <View style={styles.countBadge}>
                <Text style={styles.countBadgeText}>
                  {bankAccounts?.length}
                </Text>
              </View>
            </View>

            {/* Account Cards */}
            {bankAccounts?.map(account => (
              <View
                key={account.id}
                style={[
                  styles.accountCard,
                  account.isDefault ? styles.defaultCard : null,
                ]}
              >
                {/* Top color strip for default account */}
                {account.isDefault && <View style={styles.cardTopStrip} />}

                <View style={styles.cardBody}>
                  {/* Card Header Row */}
                  <View style={styles.cardHeaderRow}>
                    <View style={styles.cardHeaderLeft}>
                      <View style={styles.bankIconCircle}>
                        <ClipboardIcon size={22} color={colors.primary} />
                      </View>
                      <View style={styles.cardTitleGroup}>
                        <Text style={styles.bankName} numberOfLines={1}>
                          {account.bankName}
                        </Text>
                        <Text style={styles.holderName} numberOfLines={1}>
                          {account.accountHolderName}
                        </Text>
                      </View>
                    </View>

                    {/* Status Badges */}
                    <View style={styles.badgeRow}>
                      {account.isDefault && (
                        <View style={styles.defaultBadge}>
                          <Text style={styles.defaultBadgeText}>DEFAULT</Text>
                        </View>
                      )}
                      <View
                        style={
                          account.isVerified
                            ? styles.verifiedBadge
                            : styles.unverifiedBadge
                        }
                      >
                        <Text
                          style={
                            account.isVerified
                              ? styles.verifiedBadgeText
                              : styles.unverifiedBadgeText
                          }
                        >
                          {account.isVerified ? 'VERIFIED' : 'PENDING'}
                        </Text>
                      </View>
                    </View>
                  </View>

                  <View style={styles.divider} />

                  {/* Fields Grid */}
                  <View style={styles.fieldsGrid}>
                    <View style={styles.fieldItem}>
                      <Text style={styles.fieldLabel}>Account Number</Text>
                      <Text style={styles.fieldValueMasked}>
                        {maskAccountNumber(account.accountNumber)}
                      </Text>
                    </View>

                    <View style={styles.fieldItem}>
                      <Text style={styles.fieldLabel}>IFSC Code</Text>
                      <Text style={styles.fieldValue}>
                        {account.ifscCode || '—'}
                      </Text>
                    </View>

                    {account.branchName ? (
                      <View style={styles.fieldItem}>
                        <Text style={styles.fieldLabel}>Branch</Text>
                        <Text style={styles.fieldValue} numberOfLines={1}>
                          {account.branchName}
                        </Text>
                      </View>
                    ) : null}

                    <View style={styles.fieldItem}>
                      <Text style={styles.fieldLabel}>Owner Type</Text>
                      <Text style={styles.fieldValue}>
                        {account.ownerType || '—'}
                      </Text>
                    </View>
                  </View>

                  <View style={styles.divider} />

                  {/* Card Footer */}
                  <View style={styles.cardFooter}>
                    <Text style={styles.addedAtText}>
                      Added {formatDate(account.createdAt)}
                    </Text>
                    {account.isVerified && (
                      <CheckCircleIcon size={16} color={colors.success} />
                    )}
                  </View>
                </View>
              </View>
            ))}
          </>
        )}

        {/* Add Bank Account Button */}
        <TouchableOpacity
          style={styles.addButton}
          onPress={handleAddAccount}
          activeOpacity={0.8}
        >
          <View style={styles.addButtonIcon}>
            <Text style={styles.addButtonIconText}>+</Text>
          </View>
          <Text style={styles.addButtonText}>Add Bank Account</Text>
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
};

export default BankDetailsScreen;
