'use client';

import React, { useEffect, useState, useCallback } from 'react';
import {
  Card, Table, Checkbox, Radio, Select, Tag, Button, Space,
  Form, message, Spin, Input, Empty,
} from 'antd';
import { SaveOutlined } from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import { getClients, getClientApiKeys, getPermission, updatePermission } from '@/services/api';

interface ClientRecord { id: number; client_no?: string; name: string; client_type: string; api_keys: ApiKeyItem[]; }
interface ApiKeyItem { id: number; api_key: string; status: number; }
interface PermData {
  id: number; api_key_id: number; allow_chuku: number; allow_ruku: number;
  allow_full_data: number; filter_field?: string; filter_values?: string[];
}

const FILTER_FIELDS = [
  { label: '销方全称', value: '销方全称' },
  { label: '供方全称', value: '供方全称' },
  { label: '销方序号', value: '销方序号' },
  { label: '供方序号', value: '供方序号' },
];

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' },
};

export default function PermissionsPage() {
  const [clients, setClients] = useState<ClientRecord[]>([]);
  const [selectedKeyId, setSelectedKeyId] = useState<number | null>(null);
  const [selectedClient, setSelectedClient] = useState<ClientRecord | null>(null);
  const [perm, setPerm] = useState<PermData | null>(null);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [filterValues, setFilterValues] = useState<string[]>([]);
  const [newFilterValue, setNewFilterValue] = useState('');
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<Record<string, unknown>>({});

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

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

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

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

  const getAutoFilterInfo = (client: ClientRecord, allowChuku: boolean, allowRuku: boolean) => {
    const rules: { label: string; field?: string; value?: string; disabled: boolean }[] = [];
    if (allowChuku) {
      rules.push({ label: '出库规则', field: '销方全称', value: client.name, disabled: false });
    } else {
      rules.push({ label: '出库规则', disabled: true });
    }
    if (allowRuku) {
      rules.push({ label: '入库规则', field: '供方全称', value: client.name, disabled: false });
    } else {
      rules.push({ label: '入库规则', disabled: true });
    }
    return rules;
  };

  const loadPermission = useCallback(async (keyId: number, client: ClientRecord) => {
    setLoading(true);
    try {
      const res = await getPermission(keyId);
      const p = res.data;

      if (p) {
        setPerm(p);
        form.setFieldsValue({
          allow_chuku: !!p.allow_chuku,
          allow_ruku: !!p.allow_ruku,
          data_mode: p.data_mode || 'filter',
          filter_field: p.filter_field,
        });
        setFilterValues(p.filter_values || []);
      } else {
        setPerm(null);
        form.setFieldsValue({
          allow_chuku: false,
          allow_ruku: false,
          data_mode: 'filter',
          filter_field: undefined,
        });
        setFilterValues([]);
      }
    } catch (err) {
      message.error('获取权限配置失败');
    } finally {
      setLoading(false);
    }
  }, [form]);

  const handleSave = async () => {
    if (!selectedKeyId) return;
    const values = form.getFieldsValue();
    setSaving(true);
    try {
      await updatePermission(selectedKeyId, {
        allow_chuku: values.allow_chuku ? 1 : 0,
        allow_ruku: values.allow_ruku ? 1 : 0,
        allow_full_data: values.data_mode === 'full' ? 1 : 0,
        data_mode: values.data_mode,
        filter_field: values.data_mode === 'full' ? null : values.filter_field,
        filter_values: values.data_mode === 'full' ? null : filterValues,
      });
      message.success('权限配置已保存');
    } catch (err: any) {
      message.error(err.response?.data?.detail || '保存失败');
    } finally {
      setSaving(false);
    }
  };

  const addFilterValue = () => {
    const v = newFilterValue.trim();
    if (v && !filterValues.includes(v)) {
      setFilterValues([...filterValues, v]);
      setNewFilterValue('');
    }
  };

  const removeFilterValue = (val: string) => {
    setFilterValues(filterValues.filter(v => v !== val));
  };

  const dataMode = Form.useWatch('data_mode', form);
  const allowChuku = Form.useWatch('allow_chuku', form);
  const allowRuku = Form.useWatch('allow_ruku', form);

  return (
    <AdminLayout>
      <div style={{ position: 'relative', height: 'calc(100vh - 120px)' }}>
        <Card
          title="客户 / API Key"
          style={{ width: 420, height: '100%', display: 'flex', flexDirection: 'column' }}
          extra={
            <Space>
              <Input
                placeholder="客户序号"
                style={{ width: 100 }}
                value={filters.client_no as string}
                onChange={(e) => handleSearchChange('client_no', e.target.value)}
              />
              <Input
                placeholder="客户名称"
                style={{ width: 120 }}
                value={filters.name as string}
                onChange={(e) => handleSearchChange('name', e.target.value)}
              />
              <Select
                placeholder="类型"
                allowClear
                style={{ width: 100 }}
                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} size="small">重置</Button>
            </Space>
          }
        >
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {clients.length === 0 ? <Empty description="暂无客户" /> : clients.map(client => (
              <div key={client.id} style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontWeight: 600, fontSize: 14 }}>{client.name}</span>
                  <Tag color={TYPE_MAP[client.client_type]?.color}>
                    {TYPE_MAP[client.client_type]?.label}
                  </Tag>
                </div>
                {client.client_no && (
                  <div style={{ fontSize: 12, color: '#999', marginBottom: 4 }}>序号：{client.client_no}</div>
                )}
                {client.api_keys?.map(key => (
                  <div
                    key={key.id}
                    onClick={() => {
                      setSelectedKeyId(key.id);
                      setSelectedClient(client);
                      loadPermission(key.id, client);
                    }}
                    style={{
                      padding: '10px 14px', cursor: 'pointer', borderRadius: 8, marginBottom: 6,
                      background: selectedKeyId === key.id ? '#e6f7ff' : '#fff',
                      border: selectedKeyId === key.id ? '1px solid #1890ff' : '1px solid #e8e8e8',
                      transition: 'all 0.2s',
                    }}
                  >
                    <div style={{ fontFamily: 'monospace', fontSize: 13, color: '#333' }}>{key.api_key}</div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 6 }}>
                      <Tag color={key.status === 1 ? 'green' : 'red'}>
                        {key.status === 1 ? '启用' : '禁用'}
                      </Tag>
                    </div>
                  </div>
                ))}
                {(!client.api_keys || client.api_keys.length === 0) && (
                  <div style={{ color: '#bbb', fontSize: 12, padding: '8px 12px', border: '1px dashed #e8e8e8', borderRadius: 6 }}>
                    暂无 API Key，请先创建
                  </div>
                )}
              </div>
            ))}
          </div>
        </Card>

        <Card title="权限配置" style={{ position: 'fixed', left: 460, right: 24, top: 96, bottom: 24, display: 'flex', flexDirection: 'column' }}>
          {!selectedKeyId ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Empty description="请从左侧选择一个 API Key" />
            </div>
          ) : loading ? (
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Spin size="large" />
            </div>
          ) : (
            <div style={{ flex: 1, overflowY: 'auto' }}>
              <Form form={form} layout="vertical">
                <div style={{ maxWidth: 600 }}>
                  <Form.Item label="接口权限">
                    <div style={{ display: 'flex', gap: 24 }}>
                      <Form.Item name="allow_chuku" valuePropName="checked" style={{ marginBottom: 0 }}>
                        <Checkbox disabled={dataMode === 'full'}>销售数据查询接口</Checkbox>
                      </Form.Item>
                      <Form.Item name="allow_ruku" valuePropName="checked" style={{ marginBottom: 0 }}>
                        <Checkbox disabled={dataMode === 'full'}>入库数据查询接口</Checkbox>
                      </Form.Item>
                    </div>
                  </Form.Item>

                  <Form.Item label="数据过滤规则" name="data_mode" initialValue="filter">
                    <Radio.Group>
                      <Radio value="filter">按接口权限过滤</Radio>
                      {/* <Radio value="custom">自定义过滤规则</Radio> */}
                      <Radio value="full">允许全量数据（核心大户）</Radio>
                    </Radio.Group>
                  </Form.Item>

                  {dataMode === 'filter' && selectedClient && (() => {
                    const autoRules = getAutoFilterInfo(selectedClient, allowChuku, allowRuku);
                    return (
                      <div style={{ padding: 16, background: '#f5f5f5', borderRadius: 8, marginTop: 8 }}>
                        <div style={{ fontSize: 14, color: '#666', marginBottom: 12 }}>
                          根据接口权限自动生成过滤规则：
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                          {autoRules.map((rule, idx) => (
                            <div key={idx} style={{ display: 'flex', gap: 12, fontSize: 14 }}>
                              <span style={{ fontWeight: 600, color: '#1890ff' }}>{rule.label}：</span>
                              {rule.disabled ? (
                                <span style={{ color: '#999' }}>无{rule.label === '出库规则' ? '出库' : '入库'}查询权限</span>
                              ) : (
                                <>
                                  <span>过滤字段：</span>
                                  <span style={{ fontWeight: 600 }}>{rule.field}</span>
                                  <span style={{ marginLeft: 16 }}>过滤值：</span>
                                  <span style={{ fontWeight: 600 }}>{rule.value}</span>
                                </>
                              )}
                            </div>
                          ))}
                        </div>
                      </div>
                    );
                  })()}

                  {dataMode === 'custom' && (
                    <>
                      <Form.Item label="过滤字段" name="filter_field" rules={[{ required: true, message: '请选择过滤字段' }]}>
                        <Select
                          options={FILTER_FIELDS}
                          placeholder="请选择过滤字段"
                          style={{ width: 200 }}
                        />
                      </Form.Item>

                      <Form.Item label="过滤值">
                        <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
                          <Input
                            placeholder="输入过滤值后按回车或点击添加"
                            value={newFilterValue}
                            onChange={e => setNewFilterValue(e.target.value)}
                            onPressEnter={addFilterValue}
                            style={{ width: 300 }}
                          />
                          <Button onClick={addFilterValue}>添加</Button>
                        </div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                          {filterValues.map(v => (
                            <Tag key={v} closable onClose={() => removeFilterValue(v)} color="blue">
                              {v}
                            </Tag>
                          ))}
                          {filterValues.length === 0 && <span style={{ color: '#999', fontSize: 13 }}>暂未添加过滤值</span>}
                        </div>
                      </Form.Item>
                    </>
                  )}

                  <Form.Item style={{ marginTop: 24 }}>
                    <Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave} size="large">
                      保存权限配置
                    </Button>
                  </Form.Item>
                </div>
              </Form>
            </div>
          )}
        </Card>
      </div>
    </AdminLayout>
  );
}
