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

interface ResourceDetailDrawerProps {
  resource: Resource;
  open: boolean;
  onClose: () => void;
}

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

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

  const {
    data: roleData,
    loading: roleLoading,
    fetchData: fetchRoles,
  } = useFetchData('role/findMany', 'post', undefined, true);

  useEffect(() => {
    if (open) {
      fetchPageResources({
        where: { resourceId: resource.id },
        include: {
          page: {
            select: {
              id: true,
              name: true,
              code: true,
              zhName: true,
              enName: true,
            },
          },
        },
        take: 1000,
      });
      // Query roles with filtered roleResources for this resource
      fetchRoles({
        where: {
          roleResources: {
            some: { resourceId: resource.id },
          },
        },
        include: {
          roleResources: {
            where: { resourceId: resource.id },
          },
        },
        take: 1000,
      });
    }
  }, [open, resource.id]);

  const pages = useMemo(() => {
    const list: any[] = Array.isArray(pageResourceData?.data)
      ? pageResourceData.data
      : [];
    return list.map((item: any) => {
      const page = item.page;
      const pageName = isChinese
        ? page?.zhName || page?.name || '-'
        : page?.enName || page?.name || '-';
      return {
        key: item.id,
        pageName,
        pageCode: page?.code || '-',
        actions: Array.isArray(item.actions) ? item.actions : [],
      };
    });
  }, [pageResourceData]);

  const roles = useMemo(() => {
    const list: any[] = Array.isArray(roleData?.data) ? roleData.data : [];
    return list.map((item: any) => {
      const roleResource = item.roleResources?.[0];
      const actions = roleResource?.actions;
      return {
        key: item.id,
        roleName: item.name || '-',
        roleCode: item.code || '-',
        actions: Array.isArray(actions) ? actions : [],
      };
    });
  }, [roleData]);

  const permissionColumns = [
    {
      title: 'Permissions',
      dataIndex: 'actions',
      render: (actions: string[]) => (
        <Space size={[0, 4]} wrap>
          {actions.map((a) => (
            <Tag key={a}>{a}</Tag>
          ))}
        </Space>
      ),
    },
  ];

  return (
    <Drawer
      title={`Resource: ${resource.name}`}
      open={open}
      onClose={onClose}
      width={560}
      destroyOnClose
    >
      <Descriptions
        column={1}
        size="small"
        bordered
        style={{ marginBottom: 16 }}
      >
        <Descriptions.Item label="Code">{resource.code}</Descriptions.Item>
        <Descriptions.Item label="Name">{resource.name}</Descriptions.Item>
        {resource.description && (
          <Descriptions.Item label="Description">
            {resource.description}
          </Descriptions.Item>
        )}
      </Descriptions>

      <Tabs
        items={[
          {
            key: 'pages',
            label: `Referenced by Pages (${pages.length})`,
            children: (
              <Table
                dataSource={pages}
                loading={pageLoading}
                rowKey="key"
                size="small"
                pagination={pages.length > 10 ? { pageSize: 10 } : false}
                columns={[
                  { title: 'Page Name', dataIndex: 'pageName', width: '35%' },
                  { title: 'Page Code', dataIndex: 'pageCode', width: '25%' },
                  ...permissionColumns,
                ]}
              />
            ),
          },
          {
            key: 'roles',
            label: `Visible to Roles (${roles.length})`,
            children: (
              <Table
                dataSource={roles}
                loading={roleLoading}
                rowKey="key"
                size="small"
                pagination={roles.length > 10 ? { pageSize: 10 } : false}
                columns={[
                  { title: 'Role Name', dataIndex: 'roleName', width: '35%' },
                  ...permissionColumns,
                ]}
              />
            ),
          },
        ]}
      />
    </Drawer>
  );
};
