import { StatusBadge } from '@/components/ui/status-badge';
import { Ionicons } from '@expo/vector-icons';
import React, { useState } from 'react';
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

type CustomerStatus = '全部' | '待上传' | '解析中' | '已分析' | '已匹配' | '审核中';

type Customer = {
  id: string;
  name: string;
  phone: string;
  loanType: string;
  status: Exclude<CustomerStatus, '全部'>;
  score?: string;
  note: string;
  updatedAt: string;
};

const FILTERS: CustomerStatus[] = ['全部', '待上传', '解析中', '已分析', '已匹配', '审核中'];

const CUSTOMERS: Customer[] = [
  {
    id: '1',
    name: '张德发',
    phone: '138****8888',
    loanType: '经营贷',
    status: '审核中',
    score: 'B+',
    note: '申请材料已补齐，等待风控初审',
    updatedAt: '今天 10:42',
  },
  {
    id: '2',
    name: '李美华',
    phone: '139****6666',
    loanType: '消费贷',
    status: '已匹配',
    score: 'A',
    note: '已匹配 3 个可推荐产品，待沟通方案',
    updatedAt: '今天 09:18',
  },
  {
    id: '3',
    name: '王大锤',
    phone: '137****3333',
    loanType: '房抵贷',
    status: '已分析',
    score: 'B',
    note: '征信报告已生成，建议先推进抵押类产品',
    updatedAt: '昨天 16:20',
  },
  {
    id: '4',
    name: '赵丽',
    phone: '136****1111',
    loanType: '消费贷',
    status: '待上传',
    note: '客户资料已建档，待上传征信文件',
    updatedAt: '2天前',
  },
  {
    id: '5',
    name: '钱进',
    phone: '135****9999',
    loanType: '经营贷',
    status: '解析中',
    note: '系统正在解析征信数据，预计 30-90 秒完成',
    updatedAt: '刚刚',
  },
];

function getBadgeVariant(status: Customer['status']) {
  switch (status) {
    case '待上传':
      return 'error' as const;
    case '解析中':
    case '审核中':
      return 'secondary' as const;
    case '已分析':
      return 'primary' as const;
    case '已匹配':
      return 'tertiary' as const;
    default:
      return 'secondary' as const;
  }
}

function getPrimaryAction(status: Customer['status']) {
  switch (status) {
    case '待上传':
      return '上传征信';
    case '解析中':
      return '查看进度';
    default:
      return '查看报告';
  }
}

export default function CustomerScreens() {
  const [search, setSearch] = useState('');
  const [activeFilter, setActiveFilter] = useState<CustomerStatus>('全部');

  const filteredCustomers = CUSTOMERS.filter((item) => {
    const matchSearch =
      search.trim().length === 0 ||
      item.name.includes(search) ||
      item.phone.includes(search);
    const matchFilter = activeFilter === '全部' || item.status === activeFilter;
    return matchSearch && matchFilter;
  });

  return (
    <SafeAreaView className="flex-1 bg-surface" edges={['top']}>
      <ScrollView
        className="flex-1"
        contentContainerClassName="px-5 pt-3 pb-24"
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        <Text className="mb-2 text-3xl font-extrabold tracking-tight text-on-surface">
          客户
        </Text>
        <Text className="mb-5 text-base leading-7 text-on-surface-variant">
          统一跟进客户资料、征信进度和产品匹配状态
        </Text>

        <View className="mb-3 flex-row items-center rounded-2xl bg-surface-container-low px-4 py-3">
          <Ionicons name="search-outline" size={20} color="#737686" />
          <TextInput
            value={search}
            onChangeText={setSearch}
            placeholder="搜索客户姓名 / 手机号"
            placeholderTextColor="#9ca3af"
            className="ml-3 flex-1 p-0 text-base text-on-surface"
          />
          {search.length > 0 ? (
            <Pressable hitSlop={8} onPress={() => setSearch('')}>
              <Ionicons name="close-circle" size={20} color="#c3c6d7" />
            </Pressable>
          ) : null}
        </View>

        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerClassName="gap-2 pb-1"
          className="mb-5"
        >
          {FILTERS.map((filter) => {
            const active = activeFilter === filter;
            return (
              <Pressable
                key={filter}
                onPress={() => setActiveFilter(filter)}
                className={`rounded-full px-4 py-2 ${
                  active ? 'bg-primary-container' : 'bg-surface-container-lowest'
                }`}
                style={({ pressed }) => ({
                  opacity: pressed ? 0.84 : 1,
                })}
              >
                <Text
                  className={`text-sm font-bold ${
                    active ? 'text-on-primary' : 'text-on-surface-variant'
                  }`}
                >
                  {filter}
                </Text>
              </Pressable>
            );
          })}
        </ScrollView>

        <View className="gap-3">
          {filteredCustomers.length === 0 ? (
            <View className="items-center rounded-2xl border border-outline-variant bg-surface-container-lowest px-6 py-14">
              <Ionicons name="people-outline" size={44} color="#c3c6d7" />
              <Text className="mt-4 text-base text-on-surface-variant">暂无匹配客户</Text>
            </View>
          ) : (
            filteredCustomers.map((item) => (
              <Pressable
                key={item.id}
                className="rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-4"
                style={({ pressed }) => ({
                  opacity: pressed ? 0.93 : 1,
                  transform: [{ scale: pressed ? 0.995 : 1 }],
                })}
              >
                <View className="mb-3 flex-row items-start justify-between gap-3">
                  <View className="flex-1 flex-row items-center gap-3">
                    <View className="h-11 w-11 items-center justify-center rounded-full bg-primary-fixed">
                      <Text className="text-base font-bold text-primary">{item.name[0]}</Text>
                    </View>
                    <View className="flex-1">
                      <Text className="text-lg font-bold text-on-surface">{item.name}</Text>
                      <Text className="mt-1 text-sm text-on-surface-variant">
                        {item.phone}
                      </Text>
                    </View>
                  </View>
                  <StatusBadge
                    text={item.status}
                    variant={getBadgeVariant(item.status)}
                  />
                </View>

                <Text className="mb-2.5 text-sm leading-6 text-on-surface-variant">
                  {item.note}
                </Text>

                <View className="mb-3 flex-row flex-wrap items-center gap-3">
                  <View className="flex-row items-center gap-1">
                    <Ionicons name="document-text-outline" size={14} color="#737686" />
                    <Text className="text-xs text-on-surface-variant">{item.loanType}</Text>
                  </View>
                  {item.score ? (
                    <View className="flex-row items-center gap-1">
                      <Ionicons name="analytics-outline" size={14} color="#737686" />
                      <Text className="text-xs text-on-surface-variant">
                        评分 {item.score}
                      </Text>
                    </View>
                  ) : null}
                  <Text className="ml-auto text-xs text-outline">{item.updatedAt}</Text>
                </View>

                <View className="flex-row gap-3">
                  <Pressable
                    className="flex-1 items-center rounded-xl bg-primary-container py-2.5"
                    style={({ pressed }) => ({
                      opacity: pressed ? 0.88 : 1,
                    })}
                  >
                    <Text className="text-sm font-bold text-on-primary">
                      {getPrimaryAction(item.status)}
                    </Text>
                  </Pressable>
                  <Pressable
                    className="flex-1 items-center rounded-xl bg-surface-container-high py-2.5"
                    style={({ pressed }) => ({
                      opacity: pressed ? 0.88 : 1,
                    })}
                  >
                    <Text className="text-sm font-semibold text-on-surface">编辑资料</Text>
                  </Pressable>
                </View>
              </Pressable>
            ))
          )}
        </View>
      </ScrollView>

      <View className="absolute bottom-7 right-5">
        <Pressable
          className="h-14 w-14 items-center justify-center rounded-full bg-primary-container"
          style={({ pressed }) => ({
            opacity: pressed ? 0.88 : 1,
            transform: [{ scale: pressed ? 0.94 : 1 }],
          })}
        >
          <Ionicons name="person-add" size={22} color="#ffffff" />
        </Pressable>
      </View>
    </SafeAreaView>
  );
}
