import { SectionHeader } from '@/components/ui/section-header';
import api, { ListResponse } from '@/utils/api';
import { useSWC } from '@/utils/cache';
import { ActivityIndicator } from '@ant-design/react-native';
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect } from 'expo-router';
import React, { useCallback } from 'react';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { UploadComponent } from '../../components/upload';



type AnalysisRecord = {
  id: string;
  createtime: string;
  status: 'pending' | 'completed' | 'failed' | 'canceled';
  score?: string;
  customer_name?: string;
  name?: string;
};

export default function AnalyticsScreen() {
  const { data: list, loading, error, load, refresh } = useSWC<ListResponse<AnalysisRecord>>("credit_index_list", async () => {
    return api.post("credit/list", { size: 10 });
  }, {
    cacheOnly: true,
    cacheTimeout: 120,
    autoStart: false,
  })


  useFocusEffect(
    useCallback(() => {
      load();
    }, [])
  );

  return (
    <SafeAreaView className="flex-1 bg-surface" edges={['top']}>
      <ScrollView
        className="flex-1"
        contentContainerClassName="px-5 pt-3 pb-24"
        showsVerticalScrollIndicator={false}
      >
        <Text className="mb-2 text-3xl font-extrabold tracking-tight text-on-surface">
          征信分析
        </Text>

        <View className="mb-3 rounded-2xl border border-outline-variant bg-surface-container-lowest p-4">
          <Text className="mb-3 text-xs font-bold uppercase tracking-widest text-outline">
            选择客户
          </Text>
          <Pressable
            className="flex-row items-center rounded-2xl bg-surface-container-low px-4 py-3.5"
            style={({ pressed }) => ({
              opacity: pressed ? 0.9 : 1,
            })}
          >
            <Ionicons name="person-outline" size={18} color="#737686" />
            <Text className="ml-3 flex-1 text-base font-medium text-on-surface">
              张德发（138****8888）
            </Text>
            <Ionicons name="chevron-down" size={18} color="#c3c6d7" />
          </Pressable>
        </View>

        <UploadComponent onCompolete={() => { refresh() }} />



        <SectionHeader title="解析记录" actionText="查看全部" />
        <View className="gap-3">
          {loading === true && <ActivityIndicator />}
          {list?.list?.map((record) => (
            <Pressable
              key={record.id}
              className="flex-row items-center rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-3.5"
              style={({ pressed }) => ({
                opacity: pressed ? 0.93 : 1,
              })}
            >
              <View
                className={`mr-3 h-11 w-11 items-center justify-center rounded-full ${record.status === 'completed'
                  ? 'bg-green-50'
                  : record.status === 'pending'
                    ? 'bg-blue-50'
                    : 'bg-error-container'
                  }`}
              >
                <Ionicons
                  name={
                    record.status === 'completed'
                      ? 'checkmark-circle'
                      : record.status === 'pending'
                        ? 'hourglass-outline'
                        : 'alert-circle'
                  }
                  size={20}
                  color={
                    record.status === 'completed'
                      ? '#16a34a'
                      : record.status === 'pending'
                        ? '#2563eb'
                        : '#ba1a1a'
                  }
                />
              </View>

              <View className="flex-1">
                <View className="mb-1 flex-row items-center justify-between gap-3">
                  <Text className="text-base font-bold text-on-surface">
                    {record.customer_name || record.name || '客户'}
                  </Text>
                  <Text className="text-xs text-on-surface-variant">{record.createtime}</Text>
                </View>
                {(record.status === 'pending' || record.status == 'failed') && (
                  <View>
                    <View className="mb-2 flex-row items-center justify-between">
                      <Text className="text-sm text-on-surface-variant">...</Text>
                      <Text className="text-sm font-bold text-primary">
                        {record.score}
                      </Text>
                    </View>

                  </View>)}

                {record.status === 'completed' && (
                  <View>
                    <View className="mb-2 flex-row items-center justify-between">
                      <Text className="text-sm text-on-surface-variant">...</Text>
                      <Text className="text-sm font-bold text-primary">
                        {record.score}
                      </Text>
                    </View>
                    <View className="h-1.5 rounded-full bg-surface-container">
                      <View
                        className="h-full rounded-full bg-primary-container"
                        style={{ width: '10%' }}
                      />
                    </View>
                  </View>)}
                {record.status === 'canceled' && (
                  <Text className="text-sm text-error">解析失败，请联系管理员</Text>
                )}

              </View>

              <Ionicons name="chevron-forward" size={18} color="#c3c6d7" />
            </Pressable>
          ))}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
