import { MaterialCommunityIcons } from '@expo/vector-icons';
import * as Clipboard from 'expo-clipboard';
import { router, useLocalSearchParams } from 'expo-router';
import { Alert, Pressable, ScrollView, Share, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ScreenHeader } from '../../src/components/ScreenHeader';

function money(value?: string | number) {
  return `₦${Number(value || 0).toLocaleString()}`;
}

function rowLabel(value?: string | number) {
  return value || value === 0 ? String(value) : '-';
}

export default function ReceiptScreen() {
  const params = useLocalSearchParams<{
    type?: string;
    reference?: string;
    service?: string;
    company?: string;
    device_id?: string;
    network?: string;
    phone?: string;
    plan_name?: string;
    amount?: string;
    charged?: string;
    balance_after?: string;
    provider_reference?: string;
    status?: string;
    message?: string;
    timestamp?: string;
  }>();

  const reference = params.reference ?? '';
  const status = String(params.status ?? 'success').toLowerCase();
  const isSuccess = status === 'success' || status === 'processing';
  const iconName = isSuccess ? 'check-circle' : 'close-circle';
  const iconColor = isSuccess ? '#16A34A' : '#DC2626';
  const iconBg = isSuccess ? '#ECFDF3' : '#FEF2F2';
  const subtitle = isSuccess ? 'Transaction completed.' : 'Transaction failed and wallet was refunded.';

  const copy = async () => {
    await Clipboard.setStringAsync(reference);
    Alert.alert('Copied', 'Reference copied to clipboard.');
  };

  const share = async () => {
    await Share.share({
      message: [
        `PPay ${params.type ?? 'Transaction'} receipt`,
        `Reference: ${reference}`,
        `Status: ${params.status ?? '-'}`,
      ].join('\n'),
    });
  };

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView contentContainerStyle={styles.container}>
        <ScreenHeader title="Receipt" subtitle={subtitle} onBack={() => router.back()} />
        <View style={styles.card}>
          <View style={[styles.iconWrap, { backgroundColor: iconBg }]}>
            <MaterialCommunityIcons name={iconName as any} size={44} color={iconColor} />
          </View>
          <Text style={styles.type}>{params.type ?? 'Transaction'}</Text>
          <Text style={styles.ref}>{reference || '-'}</Text>

          <View style={styles.detailGrid}>
            <Detail label="Status" value={rowLabel(params.status)} />
            <Detail label="Date & Time" value={rowLabel(params.timestamp ? new Date(params.timestamp).toLocaleString() : '')} />
            <Detail label="Service" value={rowLabel(params.service)} />
            <Detail label="Provider Ref" value={rowLabel(params.provider_reference)} />
            <Detail label="Company / Network" value={rowLabel(params.company ?? params.network)} />
            <Detail label="Phone / Device" value={rowLabel(params.phone ?? params.device_id)} />
            <Detail label="Plan" value={rowLabel(params.plan_name)} />
            <Detail label="Amount" value={money(params.amount)} />
            <Detail label="Charges" value={money(params.charged)} />
            <Detail label="Wallet After" value={money(params.balance_after)} />
          </View>

          {params.message ? <Text style={styles.message}>{params.message}</Text> : null}

          <View style={styles.actions}>
            <Pressable style={styles.button} onPress={copy}><Text style={styles.buttonText}>Copy Ref</Text></Pressable>
            <Pressable style={styles.button} onPress={share}><Text style={styles.buttonText}>Share</Text></Pressable>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

function Detail({ label, value }: { label: string; value: string }) {
  return (
    <View style={styles.detailItem}>
      <Text style={styles.detailLabel}>{label}</Text>
      <Text style={styles.detailValue}>{value}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#F4FAF7' },
  container: { padding: 20, paddingBottom: 40 },
  card: { backgroundColor: '#fff', borderRadius: 24, padding: 20, borderWidth: 1, borderColor: '#D8E7DF' },
  iconWrap: { width: 64, height: 64, borderRadius: 20, alignItems: 'center', justifyContent: 'center', marginBottom: 12, alignSelf: 'center' },
  type: { fontSize: 18, fontWeight: '900', color: '#062117', textAlign: 'center' },
  ref: { fontSize: 16, fontWeight: '700', color: '#475569', textAlign: 'center', marginTop: 4 },
  detailGrid: { gap: 12, marginTop: 18 },
  detailItem: { backgroundColor: '#F8FBF9', borderRadius: 16, padding: 14, borderWidth: 1, borderColor: '#E3EFE8' },
  detailLabel: { color: '#64748B', fontSize: 12, fontWeight: '700' },
  detailValue: { color: '#062117', marginTop: 4, fontWeight: '800', lineHeight: 20 },
  message: { marginTop: 16, color: '#475569', lineHeight: 20, backgroundColor: '#F8FBF9', borderRadius: 16, padding: 14 },
  actions: { flexDirection: 'row', gap: 12, marginTop: 18 },
  button: { backgroundColor: '#0F5132', borderRadius: 14, paddingVertical: 12, paddingHorizontal: 18, flex: 1, alignItems: 'center' },
  buttonText: { color: '#fff', fontWeight: '800' },
});
