import { useMemo, useState } from 'react';
import { BankOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import {
  App as AntdApp,
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  Tag,
} from 'antd';
import type { TableProps } from 'antd';
import dayjs from 'dayjs';
import './Customers.scss';

type CustomerLevel = 'VIP' | '重点' | '普通' | '潜在';
type CustomerStatus = 'following' | 'won' | 'lost';

interface CustomerRecord {
  key: number;
  name: string;
  industry: string;
  contact: string;
  phone: string;
  level: CustomerLevel;
  owner: string;
  status: CustomerStatus;
  lastContact: string;
}

interface CustomerFormValues {
  name: string;
  industry: string;
  contact: string;
  phone: string;
  level: CustomerLevel;
  owner: string;
}

const levelOptions: CustomerLevel[] = ['VIP', '重点', '普通', '潜在'];

const levelColor: Record<CustomerLevel, string> = {
  VIP: 'purple',
  重点: 'blue',
  普通: 'geekblue',
  潜在: 'default',
};

const statusMeta: Record<CustomerStatus, { label: string; color: string }> = {
  following: { label: '跟进中', color: 'processing' },
  won: { label: '已成交', color: 'success' },
  lost: { label: '已流失', color: 'default' },
};

const initialCustomers: CustomerRecord[] = [
  {
    key: 1,
    name: '杭州云启科技有限公司',
    industry: '企业服务',
    contact: '林夏',
    phone: '13800001234',
    level: 'VIP',
    owner: '周洋',
    status: 'won',
    lastContact: '2026-10-17 09:10',
  },
  {
    key: 2,
    name: '上海灵犀网络科技',
    industry: '互联网',
    contact: '周林',
    phone: '13900002345',
    level: '重点',
    owner: '苏雯',
    status: 'following',
    lastContact: '2026-10-16 17:45',
  },
  {
    key: 3,
    name: '深圳前海智造有限公司',
    industry: '智能制造',
    contact: '苏晴',
    phone: '13700003456',
    level: 'VIP',
    owner: '周洋',
    status: 'following',
    lastContact: '2026-10-16 14:20',
  },
  {
    key: 4,
    name: '北京星辰数据服务',
    industry: '大数据',
    contact: '何俊',
    phone: '13600004567',
    level: '普通',
    owner: '杨莉',
    status: 'lost',
    lastContact: '2026-09-28 10:05',
  },
  {
    key: 5,
    name: '成都锦江数字科技',
    industry: '数字营销',
    contact: '杨帆',
    phone: '13500005678',
    level: '重点',
    owner: '赵敏',
    status: 'following',
    lastContact: '2026-10-15 16:30',
  },
  {
    key: 6,
    name: '南京云帆软件有限公司',
    industry: 'SaaS',
    contact: '王悦',
    phone: '18800006789',
    level: 'VIP',
    owner: '苏雯',
    status: 'won',
    lastContact: '2026-10-14 11:12',
  },
  {
    key: 7,
    name: '武汉光谷智能科技',
    industry: '人工智能',
    contact: '赵敏',
    phone: '18900007890',
    level: '潜在',
    owner: '杨莉',
    status: 'following',
    lastContact: '2026-10-12 15:40',
  },
  {
    key: 8,
    name: '西安丝路信息技术',
    industry: '信息技术',
    contact: '陈晨',
    phone: '18600008901',
    level: '普通',
    owner: '赵敏',
    status: 'won',
    lastContact: '2026-10-10 09:55',
  },
];

const Customers = () => {
  const [customers, setCustomers] = useState<CustomerRecord[]>(initialCustomers);
  const [keyword, setKeyword] = useState('');
  const [level, setLevel] = useState<CustomerLevel | 'all'>('all');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<CustomerRecord | null>(null);
  const [form] = Form.useForm<CustomerFormValues>();
  const { message } = AntdApp.useApp();

  const filteredCustomers = useMemo(() => {
    const normalizedKeyword = keyword.trim().toLowerCase();
    return customers.filter((customer) => {
      const matchesKeyword =
        !normalizedKeyword ||
        customer.name.toLowerCase().includes(normalizedKeyword) ||
        customer.contact.toLowerCase().includes(normalizedKeyword) ||
        customer.owner.toLowerCase().includes(normalizedKeyword);
      const matchesLevel = level === 'all' || customer.level === level;
      return matchesKeyword && matchesLevel;
    });
  }, [customers, keyword, level]);

  const openCreateModal = () => {
    setEditingCustomer(null);
    form.resetFields();
    form.setFieldsValue({ level: '普通', owner: '林夏' });
    setIsModalOpen(true);
  };

  const openEditModal = (record: CustomerRecord) => {
    setEditingCustomer(record);
    form.setFieldsValue({
      name: record.name,
      industry: record.industry,
      contact: record.contact,
      phone: record.phone,
      level: record.level,
      owner: record.owner,
    });
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (editingCustomer) {
        setCustomers((prev) =>
          prev.map((customer) =>
            customer.key === editingCustomer.key ? { ...customer, ...values } : customer,
          ),
        );
        message.success('客户信息已更新');
      } else {
        setCustomers((prev) => [
          {
            key: Date.now(),
            ...values,
            status: 'following',
            lastContact: dayjs().format('YYYY-MM-DD HH:mm'),
          },
          ...prev,
        ]);
        message.success('客户创建成功');
      }
      closeModal();
    } catch {
      // 表单校验失败时由 antd 自动展示错误信息
    }
  };

  const columns: TableProps<CustomerRecord>['columns'] = [
    {
      title: '客户名称',
      dataIndex: 'name',
      width: 280,
      render: (_value, record) => (
        <div className="customer-cell">
          <span className="customer-cell__icon">
            <BankOutlined />
          </span>
          <div className="customer-cell__meta">
            <span className="customer-cell__name">{record.name}</span>
            <span className="customer-cell__industry">{record.industry}</span>
          </div>
        </div>
      ),
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      width: 160,
      render: (_value, record) => (
        <div className="customer-contact">
          <span>{record.contact}</span>
          <small>{record.phone}</small>
        </div>
      ),
    },
    {
      title: '客户等级',
      dataIndex: 'level',
      width: 110,
      render: (value: CustomerLevel) => (
        <Tag color={levelColor[value]} bordered={false}>
          {value}
        </Tag>
      ),
    },
    { title: '负责人', dataIndex: 'owner', width: 100 },
    {
      title: '状态',
      dataIndex: 'status',
      width: 110,
      render: (value: CustomerStatus) => (
        <Tag color={statusMeta[value].color} bordered={false}>
          {statusMeta[value].label}
        </Tag>
      ),
    },
    { title: '最近联系', dataIndex: 'lastContact', width: 160 },
    {
      title: '操作',
      key: 'action',
      width: 90,
      render: (_value, record) => (
        <Button type="link" size="small" onClick={() => openEditModal(record)}>
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div className="customers-page">
      <div className="page-header">
        <div>
          <h1 className="page-header__title">客户管理</h1>
          <p className="page-header__desc">
            统一管理客户资料、跟进状态与负责人，支持按名称、联系人或等级筛选。
          </p>
        </div>
        <div className="page-header__actions">
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
            新增客户
          </Button>
        </div>
      </div>

      <Card className="filter-card" variant="borderless">
        <div className="page-toolbar">
          <Input
            allowClear
            prefix={<SearchOutlined />}
            placeholder="搜索客户 / 联系人 / 负责人"
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            style={{ width: 280 }}
          />
          <Select<CustomerLevel | 'all'>
            value={level}
            onChange={setLevel}
            style={{ width: 140 }}
            options={[
              { value: 'all', label: '全部等级' },
              ...levelOptions.map((item) => ({ value: item, label: item })),
            ]}
          />
          <span className="text-muted">共 {filteredCustomers.length} 位客户</span>
        </div>
      </Card>

      <Card className="table-card" variant="borderless">
        <Table<CustomerRecord>
          rowKey="key"
          columns={columns}
          dataSource={filteredCustomers}
          scroll={{ x: 1000 }}
          pagination={{
            pageSize: 8,
            showSizeChanger: false,
            showTotal: (total) => `共 ${total} 条`,
          }}
        />
      </Card>

      <Modal
        title={editingCustomer ? '编辑客户' : '新增客户'}
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={closeModal}
        okText={editingCustomer ? '保存' : '创建'}
        cancelText="取消"
        width={560}
        forceRender
      >
        <Form form={form} layout="vertical" preserve={false}>
          <Form.Item
            name="name"
            label="客户名称"
            rules={[{ required: true, message: '请输入客户名称' }]}
          >
            <Input placeholder="请输入公司或客户名称" maxLength={50} />
          </Form.Item>
          <Row gutter={12}>
            <Col span={12}>
              <Form.Item
                name="industry"
                label="所属行业"
                rules={[{ required: true, message: '请输入所属行业' }]}
              >
                <Input placeholder="例如：企业服务" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="level"
                label="客户等级"
                rules={[{ required: true, message: '请选择客户等级' }]}
              >
                <Select
                  options={levelOptions.map((item) => ({ value: item, label: item }))}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={12}>
            <Col span={12}>
              <Form.Item
                name="contact"
                label="联系人"
                rules={[{ required: true, message: '请输入联系人' }]}
              >
                <Input placeholder="请输入联系人姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="联系电话"
                rules={[
                  { required: true, message: '请输入联系电话' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
                ]}
              >
                <Input placeholder="请输入手机号" maxLength={11} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="owner"
            label="负责人"
            rules={[{ required: true, message: '请输入负责人' }]}
          >
            <Input placeholder="请输入负责人姓名" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Customers;
