import {
  ActionType,
  DrawerForm,
  ProColumns,
  ProFormInstance,
  ProFormSelect,
  ProTable,
} from '@ant-design/pro-components';
import { request } from '@umijs/max';
import { Button, message, Popconfirm, Space } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

interface AreaItem {
  id: number;
  name: string;
  code: string;
}

interface Country {
  code: string;
  name: string;
}

const AreaList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<AreaItem | null>(null);
  const [countries, setCountries] = useState<Country[]>([]);

  useEffect(() => {
    if (!open) return;
    if (editing) {
      formRef.current?.setFieldsValue(editing);
    } else {
      formRef.current?.resetFields();
    }
  }, [open, editing]);

  useEffect(() => {
    const fetchCountries = async () => {
      try {
        const resp = await request('/area/countries', { method: 'GET' });
        const { success, data, message: errMsg } = resp as any;
        if (!success) throw new Error(errMsg || '获取国家列表失败');
        setCountries(data || []);
      } catch (e: any) {
        message.error(e.message || '获取国家列表失败');
      }
    };
    fetchCountries();
  }, []);

  const columns: ProColumns<AreaItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      sorter: true,
      hideInSearch: true,
    },
    { title: '名称', dataIndex: 'name', width: 220 },
    { title: '编码', dataIndex: 'code', width: 160 },
    {
      title: '操作',
      dataIndex: 'actions',
      width: 240,
      hideInSearch: true,
      render: (_, row) => (
        <Space>
          <Button
            size="small"
            onClick={() => {
              setEditing(row);
              setOpen(true);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="删除区域"
            description="确认删除该区域?"
            onConfirm={async () => {
              try {
                await request(`/area/${row.id}`, {
                  method: 'DELETE',
                });
                message.success('删除成功');
                actionRef.current?.reload();
              } catch (e: any) {
                message.error(e?.message || '删除失败');
              }
            }}
          >
            <Button size="small" type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const tableRequest = async (params: Record<string, any>) => {
    try {
      const { current = 1, pageSize = 10, keyword } = params;
      const resp = await request('/area', {
        method: 'GET',
        params: {
          currentPage: current,
          pageSize,
          keyword: keyword || undefined,
        },
      });
      const { success, data, message: errMsg } = resp as any;
      if (!success) throw new Error(errMsg || '获取失败');
      return {
        data: (data?.list ?? []) as AreaItem[],
        total: data?.total ?? 0,
        success: true,
      };
    } catch (e: any) {
      message.error(e?.message || '获取失败');
      return { data: [], total: 0, success: false };
    }
  };

  const handleSubmit = async (values: AreaItem) => {
    try {
      if (editing) {
        await request(`/area/${editing.id}`, {
          method: 'PUT',
          data: values,
        });
      } else {
        await request('/area', {
          method: 'POST',
          data: values,
        });
      }
      message.success('提交成功');
      setOpen(false);
      setEditing(null);
      actionRef.current?.reload();
      return true;
    } catch (e: any) {
      message.error(e?.message || '提交失败');
      return false;
    }
  };

  return (
    <>
      <ProTable<AreaItem>
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={tableRequest}
        toolBarRender={() => [
          <Button
            key="new"
            type="primary"
            onClick={() => {
              setEditing(null);
              setOpen(true);
            }}
          >
            新增区域
          </Button>,
        ]}
      />

      <DrawerForm<AreaItem>
        title={editing ? '编辑区域' : '新增区域'}
        open={open}
        onOpenChange={setOpen}
        formRef={formRef}
        onFinish={handleSubmit}
      >
        <ProFormSelect
          name="code"
          label="国家/地区"
          options={countries.map((c) => ({
            label: `${c.name}(${c.code})`,
            value: c.code,
          }))}
          placeholder="请选择国家/地区"
          rules={[{ required: true, message: '国家/地区为必填项' }]}
          showSearch
        />
      </DrawerForm>
    </>
  );
};

export default AreaList;
