import React, { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Descriptions,
  Drawer,
  Space,
  Table,
  Tag,
  type TableColumnsType,
} from 'antd';
import { useFetchData } from '@/hooks/useFetchData';

interface PageDetailDrawerProps {
  page: {
    id: number;
    name: string;
    code?: string;
    path?: string;
    zhName?: string;
    enName?: string;
  };
  open: boolean;
  onClose: () => void;
}

export const PageDetailDrawer: React.FC<PageDetailDrawerProps> = ({
  page,
  open,
  onClose,
}) => {
  const { i18n } = useTranslation();
  const isChinese = i18n.language === 'zh_CN' || i18n.language === 'zh';

  const {
    data: pageResourceData,
    loading: pageResourceLoading,
    fetchData: fetchPageResources,
  } = useFetchData('pageResource/findMany', 'post', undefined, true);

  useEffect(() => {
    if (open) {
      fetchPageResources({
        where: { pageId: page.id },
        include: { resource: true },
      });
    }
  }, [open, page.id]);

  const resources = useMemo(() => {
    const list: any[] = Array.isArray(pageResourceData?.data)
      ? pageResourceData.data
      : [];
    return list.map((item: any) => {
      const actions = item.actions ?? item.actionList ?? item.permissions;
      let parsedActions: string[] = [];
      if (Array.isArray(actions)) {
        parsedActions = actions
          .map((a: any) =>
            typeof a === 'string' ? a : a?.name || a?.code || '',
          )
          .filter(Boolean);
      } else if (typeof actions === 'string') {
        parsedActions = actions
          .split(',')
          .map((a: string) => a.trim())
          .filter(Boolean);
      }
      return {
        key: item.id ?? `${item.pageId}-${item.resourceId}`,
        resourceName:
          item.resource?.name ||
          item.resource?.code ||
          `Resource ${item.resourceId}`,
        permissionActions: parsedActions,
      };
    });
  }, [pageResourceData]);

  const pageName = isChinese
    ? page.zhName || page.name || '-'
    : page.enName || page.name || '-';

  return (
    <Drawer
      title={`Page: ${pageName}`}
      open={open}
      onClose={onClose}
      width={480}
      destroyOnClose
    >
      <Descriptions
        column={1}
        size="small"
        bordered
        style={{ marginBottom: 16 }}
      >
        <Descriptions.Item label="Name">{pageName}</Descriptions.Item>
        {page.code && (
          <Descriptions.Item label="Code">{page.code}</Descriptions.Item>
        )}
        {page.path && (
          <Descriptions.Item label="Path">{page.path}</Descriptions.Item>
        )}
      </Descriptions>

      <Table
        dataSource={resources}
        loading={pageResourceLoading}
        rowKey="key"
        size="small"
        pagination={resources.length > 10 ? { pageSize: 10 } : false}
        columns={[
          { title: 'Resource Name', dataIndex: 'resourceName', width: '40%' },
          {
            title: 'Permission Actions',
            dataIndex: 'permissionActions',
            width: '60%',
            render: (actions: string[]) =>
              actions.length > 0 ? (
                <Space size={[4, 4]} wrap>
                  {actions.map((action) => (
                    <Tag key={action} color="blue">
                      {action}
                    </Tag>
                  ))}
                </Space>
              ) : (
                <span style={{ color: '#999' }}>-</span>
              ),
          },
        ]}
        title={() => `Assigned Resources (${resources.length})`}
      />
    </Drawer>
  );
};
