import React from 'react';
import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Popconfirm, Space } from 'antd';
import {
  CloneButton,
  DeleteButton,
  EditButton,
  ShowButton,
} from '@refinedev/antd';
import { RowAction } from '../hooks/types';
import { whenIsTrue } from '@gadmin2n/react-common';

export interface RowActionsRenderContext<T = any> {
  /** Current record */
  record: T;
  /** Record ID */
  recordId: number | string;
  /** Translation function */
  t: (key: string, defaultValue?: string) => string;
  /** Resource name */
  resourceName: string;
  /** Update handler */
  onUpdate: (values: any) => void;
  /** Is update loading */
  updateLoading: boolean;
}

export interface RowActionsProps<T = any> {
  /** Current record */
  record: T;
  /** Record ID field name */
  idField?: keyof T;
  /** Row actions from config */
  actions?: RowAction[];
  /** Handler for row update */
  onUpdate?: (id: number, values: any) => void;
  /** Is update loading */
  updateLoading?: boolean;
  /** Translation function */
  t?: (key: string, defaultValue?: string) => string;
  /** Resource name for i18n keys */
  resourceName?: string;
  /** Show edit button */
  showEdit?: boolean;
  /** Show detail/show button */
  showDetail?: boolean;
  /** Show clone button */
  showClone?: boolean;
  /** Show delete button */
  showDelete?: boolean;
  /** Show history/log button */
  showHistory?: boolean;
  /** Custom children - if provided, replaces entire default UI */
  children?:
    | React.ReactNode
    | ((context: RowActionsRenderContext<T>) => React.ReactNode);

  // Render props for fine-grained customization
  /** Custom render for edit button */
  renderEditButton?: (recordId: number | string) => React.ReactNode;
  /** Custom render for detail/show button */
  renderDetailButton?: (recordId: number | string) => React.ReactNode;
  /** Custom render for clone button */
  renderCloneButton?: (recordId: number | string) => React.ReactNode;
  /** Custom render for delete button */
  renderDeleteButton?: (recordId: number | string) => React.ReactNode;
  /** Custom render for history/log button */
  renderHistoryButton?: (recordId: number | string) => React.ReactNode;
  /** Custom render for status action buttons */
  renderStatusAction?: (
    action: RowAction,
    record: T,
    onConfirm: () => void,
    loading: boolean,
    disabled: boolean,
  ) => React.ReactNode;
  /** Custom render for more dropdown trigger */
  renderMoreTrigger?: () => React.ReactNode;
  /** Extra dropdown items to add */
  extraDropdownItems?: Array<{ key: string; label: React.ReactNode }>;
  /** Extra primary actions (rendered before More dropdown) */
  extraPrimaryActions?: React.ReactNode;
  /** Log button component (optional, for backward compatibility) */
  LogButton?: React.ComponentType<any>;
}

/**
 * Row actions component with edit, show, and more dropdown
 *
 * @example
 * // Basic usage
 * <RowActions
 *   record={record}
 *   actions={tableConfig.rowActions.actions}
 *   t={t}
 *   resourceName="audit"
 * />
 *
 * @example
 * // With custom render props
 * <RowActions
 *   {...props}
 *   renderEditButton={(id) => <MyEditButton id={id} />}
 *   renderDeleteButton={(id) => <MyDeleteButton id={id} />}
 * />
 *
 * @example
 * // Completely custom UI using children
 * <RowActions record={record}>
 *   {({ record, recordId, onUpdate }) => (
 *     <MyCustomActionsUI
 *       record={record}
 *       onEdit={() => navigate(`/edit/${recordId}`)}
 *       onUpdate={onUpdate}
 *     />
 *   )}
 * </RowActions>
 */
export function RowActions<T extends { id: number | string }>({
  record,
  idField = 'id' as keyof T,
  actions = [],
  onUpdate,
  updateLoading = false,
  t = (key, defaultValue) => defaultValue || key,
  resourceName = '',
  showEdit = true,
  showDetail = true,
  showClone = true,
  showDelete = true,
  showHistory = false,
  children,
  renderEditButton,
  renderDetailButton,
  renderCloneButton,
  renderDeleteButton,
  renderHistoryButton,
  renderStatusAction,
  renderMoreTrigger,
  extraDropdownItems = [],
  extraPrimaryActions,
  LogButton,
}: RowActionsProps<T>) {
  const recordId = record[idField] as number | string;

  const context: RowActionsRenderContext<T> = {
    record,
    recordId,
    t,
    resourceName,
    onUpdate: (values) => onUpdate?.(Number(recordId), values),
    updateLoading,
  };

  // If children is a function, call it with context
  if (typeof children === 'function') {
    return <>{children(context)}</>;
  }

  // If children is provided as ReactNode, render it directly
  if (children) {
    return <>{children}</>;
  }

  // Default rendering
  const statusActions = actions.filter(
    (action) => action.action === 'CHANGE_STATUS',
  );

  // Default button renderers
  const defaultEditButton = (id: number | string) => (
    <EditButton icon={false} type="text" size="small" recordItemId={id} />
  );

  const defaultDetailButton = (id: number | string) => (
    <ShowButton icon={false} type="text" size="small" recordItemId={id}>
      {t('table.detail', 'Detail')}
    </ShowButton>
  );

  const defaultCloneButton = (id: number | string) => (
    <CloneButton icon={false} type="text" size="small" recordItemId={id} />
  );

  const defaultDeleteButton = (id: number | string) => (
    <DeleteButton icon={false} type="text" size="small" recordItemId={id} />
  );

  const defaultHistoryButton = (id: number | string) =>
    LogButton ? (
      <LogButton
        hideText={false}
        icon={false}
        type="text"
        size="small"
        recordItemId={id}
      />
    ) : null;

  const defaultStatusAction = (
    action: RowAction,
    _record: T,
    onConfirm: () => void,
    loading: boolean,
    disabled: boolean,
  ) => (
    <Popconfirm
      placement="top"
      title={t('buttons.confirm', 'Are you sure?')}
      onConfirm={onConfirm}
      okText={t('buttons.sure', 'Yes')}
      cancelText={t('buttons.cancel', 'No')}
      disabled={disabled}
    >
      <Button loading={loading} size="small" type="text" disabled={disabled}>
        {t(`resources.${resourceName}.actions.${action.desc}`, action.desc)}
      </Button>
    </Popconfirm>
  );

  const defaultMoreTrigger = () => (
    <Button type="text" size="small">
      {t('table.more', 'More')}
      <DownOutlined />
    </Button>
  );

  // Build dropdown items
  const dropdownItems = [
    // Status change actions
    ...statusActions.map((action) => {
      const disabled = !whenIsTrue(action.when, record);
      const onConfirm = () => onUpdate?.(Number(recordId), action.values);

      return {
        key: action.desc,
        label: renderStatusAction
          ? renderStatusAction(
              action,
              record,
              onConfirm,
              updateLoading,
              disabled,
            )
          : defaultStatusAction(
              action,
              record,
              onConfirm,
              updateLoading,
              disabled,
            ),
      };
    }),
    // Clone button
    ...(showClone
      ? [
          {
            key: 'clone',
            label: renderCloneButton
              ? renderCloneButton(recordId)
              : defaultCloneButton(recordId),
          },
        ]
      : []),
    // History/Log button
    ...(showHistory || LogButton
      ? [
          {
            key: 'history',
            label: renderHistoryButton
              ? renderHistoryButton(recordId)
              : defaultHistoryButton(recordId),
          },
        ]
      : []),
    // Delete button
    ...(showDelete
      ? [
          {
            key: 'delete',
            label: renderDeleteButton
              ? renderDeleteButton(recordId)
              : defaultDeleteButton(recordId),
          },
        ]
      : []),
    // Extra items
    ...extraDropdownItems,
  ].filter((item) => item.label != null);

  return (
    <Space>
      {/* Edit button */}
      {showEdit &&
        (renderEditButton
          ? renderEditButton(recordId)
          : defaultEditButton(recordId))}

      {/* Show/Detail button */}
      {showDetail &&
        (renderDetailButton
          ? renderDetailButton(recordId)
          : defaultDetailButton(recordId))}

      {/* Extra primary actions */}
      {extraPrimaryActions}

      {/* More dropdown */}
      {dropdownItems.length > 0 && (
        <Dropdown menu={{ items: dropdownItems as any }} trigger={['click']}>
          {renderMoreTrigger ? renderMoreTrigger() : defaultMoreTrigger()}
        </Dropdown>
      )}
    </Space>
  );
}

export default RowActions;
