'use client';

import React, { useEffect, useState, useCallback } from 'react';
import {
  Table, Button, Modal, Form, Input, Select, Tag, Switch, Space, message,
  Popconfirm, Typography, Tooltip, Card,
} from 'antd';
import { PlusOutlined, KeyOutlined, DeleteOutlined, CopyOutlined, SearchOutlined } from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import {
  getClients, createClient, updateClient, toggleClient, generateApiKey,
  getClientApiKeys, deleteApiKey,
} from '@/services/api';

const { Text, Paragraph } = Typography;

const TYPE_MAP: Record<string, { label: string; color: string }> = {
  supplier: { label: '上游供应商', color: 'blue' },
  distributor: { label: '下游分销商', color: 'green' },
  hospital: { label: '医院/客户', color: 'orange' },
  other: { label: '其他', color: 'default' },
};

interface ClientRecord {
  id: number; client_no?: string; name: string; client_type: string; contact_person?: string;
  phone?: string; status: number; remark?: string; api_keys: ApiKeyItem[];
}
interface ApiKeyItem {
  id: number; api_key: string; api_secret_hash: string; status: number;
  rate_limit_per_minute: number; rate_limit_per_day: number;
}

export default function ClientsPage() {
  const [data, setData] = useState<ClientRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingClient, setEditingClient] = useState<ClientRecord | null>(null);
  const [secretModal, setSecretModal] = useState<{ visible: boolean; apiKey?: string; apiSecret?: string }>({ visible: false });
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [searchForm] = Form.useForm();

  const fetchClients = useCallback(async (params: Record<string, unknown> = {}) => {
    setLoading(true);
    try {
      const res = await getClients(params);
      setData(res.data);
    } catch (err) {
      message.error('获取客户列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchClients(); }, [fetchClients]);

  const [filters, setFilters] = useState<Record<string, unknown>>({});

  const handleSearchChange = (key: string, val: unknown) => {
    setFilters(f => ({ ...f, [key]: val || undefined }));
    fetchClients({ ...filters, [key]: val || undefined });
  };

  const handleReset = () => {
    setFilters({});
    fetchClients();
  };

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      await createClient(values);
      message.success('客户创建成功');
      setModalVisible(false);
      form.resetFields();
      fetchClients();
    } catch (err: any) {
      if (err.response?.data?.detail) message.error(err.response.data.detail);
    }
  };

  const handleEdit = (record: ClientRecord) => {
    setEditingClient(record);
    editForm.setFieldsValue({
      client_no: record.client_no,
      name: record.name,
      client_type: record.client_type,
      contact_person: record.contact_person,
      phone: record.phone,
      remark: record.remark,
    });
    setEditModalVisible(true);
  };

  const handleUpdate = async () => {
    if (!editingClient) return;
    try {
      const values = await editForm.validateFields();
      await updateClient(editingClient.id, values);
      message.success('客户信息更新成功');
      setEditModalVisible(false);
      setEditingClient(null);
      editForm.resetFields();
      fetchClients();
    } catch (err: any) {
      if (err.response?.data?.detail) message.error(err.response.data.detail);
    }
  };

  const handleToggle = async (id: number) => {
    try {
      await toggleClient(id);
      message.success('状态已更新');
      fetchClients();
    } catch (err) {
      message.error('操作失败');
    }
  };

  const handleGenerateKey = async (clientId: number) => {
    try {
      const res = await generateApiKey(clientId);
      setSecretModal({ visible: true, apiKey: res.data.api_key, apiSecret: res.data.api_secret });
      fetchClients();
    } catch (err) {
      message.error('生成密钥失败');
    }
  };

  const handleDeleteKey = async (keyId: number) => {
    try {
      await deleteApiKey(keyId);
      message.success('API Key 已删除');
      fetchClients();
    } catch (err) {
      message.error('删除失败');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    message.success('已复制到剪贴板');
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '客户序号', dataIndex: 'client_no', width: 120 },
    { title: '客户名称', dataIndex: 'name', width: 200 },
    {
      title: '客户类型', dataIndex: 'client_type', width: 120,
      render: (val: string) => {
        const t = TYPE_MAP[val] || { label: val, color: 'default' };
        return <Tag color={t.color}>{t.label}</Tag>;
      },
    },
    { title: '联系人', dataIndex: 'contact_person', width: 100 },
    { title: '手机号', dataIndex: 'phone', width: 120 },
    {
      title: '状态', dataIndex: 'status', width: 100,
      render: (val: number, record: ClientRecord) => (
        <Switch
          checked={val === 1}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onChange={() => handleToggle(record.id)}
        />
      ),
    },
    {
      title: 'API Key 数量', width: 120,
      render: (_: unknown, record: ClientRecord) => record.api_keys?.length || 0,
    },
    {
      title: '操作', width: 200, fixed: 'right' as const,
      render: (_: unknown, record: ClientRecord) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>修改</Button>
        </Space>
      ),
    },
  ];

  const expandedRowRender = (record: ClientRecord) => (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<KeyOutlined />} onClick={() => handleGenerateKey(record.id)}>
          生成密钥
        </Button>
      </div>
      <Table
        dataSource={record.api_keys || []}
        rowKey="id"
        pagination={false}
        size="small"
        columns={[
          {
            title: 'API Key', dataIndex: 'api_key',
            render: (val: string) => (
              <Space>
                <Text code copyable>{val}</Text>
              </Space>
            ),
          },
          {
            title: 'API Secret Hash', dataIndex: 'api_secret_hash',
            render: (val: string) => (
              <Space>
                <Text code copyable>{val}</Text>
              </Space>
            ),
          },
          { title: '状态', dataIndex: 'status', render: (val: number) => val === 1 ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag> },
          { title: '限流/分钟', dataIndex: 'rate_limit_per_minute' },
          { title: '限流/天', dataIndex: 'rate_limit_per_day' },
          {
            title: '操作', width: 80,
            render: (_: unknown, keyRecord: ApiKeyItem) => (
              <Popconfirm title="确认删除此 API Key？" onConfirm={() => handleDeleteKey(keyRecord.id)}>
                <Button type="link" danger icon={<DeleteOutlined />} size="small">删除</Button>
              </Popconfirm>
            ),
          },
        ]}
      />
    </div>
  );

  return (
    <AdminLayout>
      <Card
        title="上下游客户管理"
        extra={
          <Space>
            <Input
              placeholder="客户序号"
              style={{ width: 120 }}
              value={filters.client_no as string}
              onChange={(e) => handleSearchChange('client_no', e.target.value)}
            />
            <Input
              placeholder="客户名称"
              style={{ width: 150 }}
              value={filters.name as string}
              onChange={(e) => handleSearchChange('name', e.target.value)}
            />
            <Select
              placeholder="客户类型"
              allowClear
              style={{ width: 120 }}
              value={filters.client_type as string}
              onChange={(val) => handleSearchChange('client_type', val)}
              options={[
                { label: '上游供应商', value: 'supplier' },
                { label: '下游分销商', value: 'distributor' },
                { label: '医院/客户', value: 'hospital' },
                { label: '其他', value: 'other' },
              ]}
            />
            <Button onClick={handleReset}>重置</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalVisible(true)}>新建客户</Button>
          </Space>
        }
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          expandable={{ expandedRowRender }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 新建客户 Modal */}
      <Modal title="新建客户" open={modalVisible} onOk={handleCreate} onCancel={() => setModalVisible(false)} destroyOnHidden>
        <Form form={form} layout="vertical">
          <Form.Item name="client_no" label="客户序号">
            <Input placeholder="例如：C001" />
          </Form.Item>
          <Form.Item name="name" label="客户名称" rules={[{ required: true }]}>
            <Input placeholder="例如：喀喇沁旗中医蒙医医院" />
          </Form.Item>
          <Form.Item name="client_type" label="客户类型" rules={[{ required: true }]}>
            <Select placeholder="请选择">
              <Select.Option value="supplier">上游供应商</Select.Option>
              <Select.Option value="distributor">下游分销商</Select.Option>
              <Select.Option value="hospital">医院/客户</Select.Option>
              <Select.Option value="other">其他</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="contact_person" label="联系人"><Input /></Form.Item>
          <Form.Item name="phone" label="手机号"><Input /></Form.Item>
          <Form.Item name="remark" label="备注"><Input.TextArea rows={2} /></Form.Item>
        </Form>
      </Modal>

      {/* 修改客户 Modal */}
      <Modal title="修改客户" open={editModalVisible} onOk={handleUpdate} onCancel={() => setEditModalVisible(false)} destroyOnHidden>
        <Form form={editForm} layout="vertical">
          <Form.Item name="client_no" label="客户序号">
            <Input placeholder="例如：C001" />
          </Form.Item>
          <Form.Item name="name" label="客户名称" rules={[{ required: true }]}>
            <Input placeholder="例如：喀喇沁旗中医蒙医医院" />
          </Form.Item>
          <Form.Item name="client_type" label="客户类型" rules={[{ required: true }]}>
            <Select placeholder="请选择">
              <Select.Option value="supplier">上游供应商</Select.Option>
              <Select.Option value="distributor">下游分销商</Select.Option>
              <Select.Option value="hospital">医院/客户</Select.Option>
              <Select.Option value="other">其他</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item name="contact_person" label="联系人"><Input /></Form.Item>
          <Form.Item name="phone" label="手机号"><Input /></Form.Item>
          <Form.Item name="remark" label="备注"><Input.TextArea rows={2} /></Form.Item>
        </Form>
      </Modal>

      {/* API Secret 展示 */}
      <Modal
        title="API 密钥已生成"
        open={secretModal.visible}
        onCancel={() => setSecretModal({ visible: false })}
        footer={null}
        width={600}
      >
        <div style={{ background: '#fff7e6', padding: 16, borderRadius: 8, marginBottom: 16 }}>
          <Text type="warning" strong>API Secret 很重要，切勿泄漏。</Text>
        </div>
        <div style={{ marginBottom: 12 }}>
          <Text strong>API Key：</Text>
          <Paragraph code copyable style={{ marginTop: 4 }}>{secretModal.apiKey}</Paragraph>
        </div>
        <div>
          <Text strong>API Secret：</Text>
          <Paragraph code copyable style={{ marginTop: 4 }}>{secretModal.apiSecret}</Paragraph>
        </div>
      </Modal>
    </AdminLayout>
  );
}
