import { SectionHeader } from '@/components/ui/section-header';
import { StatusBadge } from '@/components/ui/status-badge';
import UIButton from '@/components/ui/UIButton';
import api from '@/utils/api';
import { useSWC } from '@/utils/cache';
import { Ionicons } from '@expo/vector-icons';

import { useFocusEffect } from 'expo-router';
import { useCallback, useState } from 'react';
import { Pressable, ScrollView, Text, View } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { UploadScreen } from '../../components/upload';



type ActivityItem = {
  id: string;
  name: string;
  loanType: string;
  time: string;
  description: string;
  badgeText: string;
  badgeVariant: 'primary' | 'secondary' | 'tertiary';
  avatarBackground: string;
  avatarColor: string;
};


const RECENT_ACTIVITIES: ActivityItem[] = [
  {
    id: '1',
    name: '张德发',
    loanType: '经营贷',
    time: '10分钟前',
    description: '申请材料已上传，等待风控初审',
    badgeText: '审核中',
    badgeVariant: 'secondary',
    avatarBackground: '#0f172a',
    avatarColor: '#ffffff',
  },
  {
    id: '2',
    name: '李美华',
    loanType: '消费贷',
    time: '2小时前',
    description: '系统匹配到 3 个符合条件的银行产品',
    badgeText: '已匹配',
    badgeVariant: 'tertiary',
    avatarBackground: '#ccfbf1',
    avatarColor: '#0f172a',
  },
  {
    id: '3',
    name: '王大锤',
    loanType: '房抵贷',
    time: '1天前',
    description: '银行面谈已完成，正在落实抵押登记',
    badgeText: '待抵押',
    badgeVariant: 'primary',
    avatarBackground: '#dcfce7',
    avatarColor: '#0f172a',
  },
];

const CHART_BARS = [22, 36, 44, 58, 34, 64, 48, 72, 52, 40];

function formatToday() {
  const date = new Date();
  const weekdays = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六',
  ];

  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${weekdays[date.getDay()]}`;
}

function getGreeting() {
  const hour = new Date().getHours();
  if (hour < 12) {
    return '早上好';
  }
  if (hour < 18) {
    return '下午好';
  }
  return '晚上好';
}

export default function HomeScreen() {
  const { data: summary, load } = useSWC<{
    pending: number;
    matched: number;
    completed: number;
  }>('home/summary', async () => {
    return api.get("share/summary");
  }, {
    cacheTimeout: 60,
    cacheOnly: false,
    autoStart: false
  });

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


  const [selectCredit, setSelectCredit] = useState(false);
  return (
    <SafeAreaView className="flex-1 bg-surface" edges={['top']}>
      <View className="h-14 flex-row items-center justify-between border-b border-outline-variant/20 bg-surface-container-lowest px-5">
        <View className="flex-row items-center gap-3">
          <View className="h-9 w-9 items-center justify-center rounded-full bg-slate-900">
            <Ionicons name="person" size={18} color="#ffffff" />
          </View>
          <Text className="text-xl font-extrabold tracking-tight text-on-surface">
            贷款助手
          </Text>
        </View>
        <Pressable hitSlop={8}>
          <Ionicons name="notifications-outline" size={24} color="#94a3b8" />
        </Pressable>
      </View>

      <ScrollView
        className="flex-1"
        contentContainerClassName="px-5 pt-4 pb-24"
        showsVerticalScrollIndicator={false}
      >
        <View className="mb-6">
          <Text className="mb-1.5 text-base tracking-wide text-on-surface-variant">
            {formatToday()}
          </Text>
          <Text className="text-3xl font-extrabold tracking-tight text-on-surface">
            {getGreeting()}，助贷人
          </Text>
        </View>

        <View className="mb-8 gap-3">


          <View className="flex-row gap-3">
            <View className="flex-1 rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-5">
              <Text className="mb-2 text-base text-on-surface-variant">已分析</Text>
              <Text className="text-4xl font-bold text-on-surface">{summary ? summary.pending : '...'}</Text>
              <View className="mt-4 h-1.5 rounded-full bg-surface-container">
                <View
                  className="h-full rounded-full bg-secondary"
                  style={{ width: '65%' }}
                />
              </View>
            </View>
            <View className="flex-1 rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-5">
              <Text className="mb-2 text-base text-on-surface-variant">待匹配</Text>
              <Text className="text-4xl font-bold text-on-surface">{summary ? summary.matched : '...'}</Text>
              <View className="mt-4 h-1.5 rounded-full bg-surface-container">
                <View
                  className="h-full rounded-full bg-tertiary-fixed-dim"
                  style={{ width: '88%' }}
                />
              </View>
            </View>
            <View className="flex-1 rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-5">
              <Text className="mb-2 text-base text-on-surface-variant">已匹配</Text>
              <Text className="text-4xl font-bold text-on-surface">{summary ? summary.completed : '...'}</Text>
              <View className="mt-4 h-1.5 rounded-full bg-surface-container">
                <View
                  className="h-full rounded-full bg-blue-600"
                  style={{ width: '88%' }}
                />
              </View>
            </View>
          </View>
        </View>

        <View className="mb-8">
          <SectionHeader title="快捷入口" />
          <View className="flex-row items-start justify-around">
            <UIButton type='primary' href="/customer/add" icon="user-add" className='flex-1'>添加客户</UIButton>
            <View className='w-5' />
            <UIButton onPress={() => setSelectCredit(true)} icon="cloud-upload" className='flex-1'>征信分析</UIButton>
          </View>
        </View>

        <View className="mb-8">
          <SectionHeader title="最近动态" actionText="查看全部" />
          <View className="gap-3">
            {RECENT_ACTIVITIES.map((item) => (
              <Pressable
                key={item.id}
                className="flex-row items-center gap-3 rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-3.5"
                style={({ pressed }) => ({
                  opacity: pressed ? 0.92 : 1,
                  transform: [{ scale: pressed ? 0.99 : 1 }],
                })}
              >
                <View
                  className="h-12 w-12 items-center justify-center rounded-full"
                  style={{ backgroundColor: item.avatarBackground }}
                >
                  <Ionicons name="person" size={20} color={item.avatarColor} />
                </View>
                <View className="flex-1">
                  <View className="mb-1 flex-row items-start justify-between gap-2">
                    <Text className="flex-1 text-xl font-bold text-on-surface">
                      {item.name} - {item.loanType}
                    </Text>
                    <Text className="text-xs text-on-surface-variant">{item.time}</Text>
                  </View>
                  <Text
                    className="text-sm leading-6 text-on-surface-variant"
                    numberOfLines={1}
                  >
                    {item.description}
                  </Text>
                </View>
                <StatusBadge text={item.badgeText} variant={item.badgeVariant} />
              </Pressable>
            ))}
          </View>
        </View>

        <View className="mb-3 h-44 overflow-hidden rounded-2xl bg-slate-950">
          <View className="absolute inset-0 bg-primary/10" />
          <View className="absolute bottom-0 right-0 h-full w-40 flex-row items-end gap-1 px-5 pb-5">
            {CHART_BARS.map((height, index) => (
              <View
                key={`${height}-${index}`}
                className="w-2 rounded-full bg-primary-container/40"
                style={{ height }}
              />
            ))}
          </View>
          <View className="absolute inset-y-0 right-0 w-1/2 bg-primary/5" />
          <View className="relative flex-1 justify-end px-5 py-5">
            <Text className="mb-3 text-3xl font-extrabold text-on-primary">
              行业洞察
            </Text>
            <Text
              className="text-base leading-7 text-white/75"
              style={{ maxWidth: 190 }}
            >
              本周 LPR 利率下调，建议优先推荐对流水稳定要求更高的产品。
            </Text>
            <Pressable
              className="mt-4 self-start rounded-full bg-surface-container-lowest px-4 py-2.5"
              style={({ pressed }) => ({
                opacity: pressed ? 0.86 : 1,
              })}
            >
              <Text className="text-sm font-bold text-inverse-surface">立即了解</Text>
            </Pressable>
          </View>
        </View>
      </ScrollView>
      <View
        className="absolute z-50 h-9 w-24 right-12 items-center justify-center rounded-full bg-primary"
        style={{ bottom: 64 + insets?.bottom || 0 }}
      >
        <Text className="text-lg font-bold text-white">
          AI 助理
        </Text>
      </View>
      <UploadScreen visible={selectCredit} onClose={() => setSelectCredit(false)} />
    </SafeAreaView>
  );
}


