import React, { useEffect, useState } from 'react';
import { Button, Space, Select, Input } from 'antd';
import { Search, RefreshCw, Edit2, Trash2, Eye } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button as UIButton } from '../ui/button';
import '../IsolationWorkListTable.css';

/** 与点位管理一致：页面最外层 */
export function MaterialPageRoot({ children }: { children: React.ReactNode }) {
  return <div className="min-h-0 w-full max-w-full space-y-4 p-6">{children}</div>;
}

/** 与 SegregationPointManagement 一致：单行 justify-between，左为筛选+搜索/重置，右为新增/批量操作 */
export function MaterialToolbarCard({
  filterRow,
  toolbarRight,
  onSearch,
  onReset,
  hideSearchButtons,
  topSlot,
}: {
  filterRow: React.ReactNode;
  toolbarRight?: React.ReactNode;
  /** hideSearchButtons 为 true 时可不传 */
  onSearch?: () => void;
  onReset?: () => void;
  /** 盘点等特殊页可自定义按钮，不显示默认搜索/重置 */
  hideSearchButtons?: boolean;
  /** 嵌入物资柜详情时：与筛选区同一张白卡顶部的 Tab 等 */
  topSlot?: React.ReactNode;
}) {
  const { t } = useTranslation();
  const showSearch = !hideSearchButtons && onSearch && onReset;
  const inner = (
    <div className="flex items-center justify-between gap-3 flex-wrap">
      <div className="flex min-w-0 flex-1 items-center gap-3 flex-wrap">
        {filterRow}
        {showSearch ? (
          <Space className="flex-shrink-0" size="small">
            <Button type="primary" icon={<Search />} onClick={onSearch}>
              {t('common.search')}
            </Button>
            <Button icon={<RefreshCw />} onClick={onReset}>
              {t('common.reset')}
            </Button>
          </Space>
        ) : null}
      </div>
      {toolbarRight != null && toolbarRight !== false ? (
        <div className="flex flex-shrink-0 justify-end">
          <Space size="small">{toolbarRight}</Space>
        </div>
      ) : null}
    </div>
  );
  if (topSlot) {
    return (
      <div className="overflow-hidden rounded-xl border border-gray-200/50 bg-white shadow-sm">
        <div className="border-b border-gray-100/80 px-2 pb-3 pt-4 sm:px-3 sm:pb-4 sm:pt-5">{topSlot}</div>
        <div className="px-5 pb-6 pt-6 sm:pb-8 sm:pt-7">{inner}</div>
      </div>
    );
  }
  return <div className="rounded-xl border border-gray-200/50 bg-white p-5 shadow-sm">{inner}</div>;
}

/** 与点位管理一致：表格白底容器 + 隔行样式类名；flush 时无外框，便于嵌入外层统一卡片 */
export function MaterialTableCard({ children, flush }: { children: React.ReactNode; flush?: boolean }) {
  return (
    <div
      className={
        flush
          ? 'bg-white isolation-work-list-table'
          : 'bg-white rounded-lg border border-gray-200 isolation-work-list-table'
      }
    >
      {children}
    </div>
  );
}

/** 与 SegregationPointManagement 底部分页条一致（加载中或无数据时不展示） */
export function MaterialPaginationBar({
  total,
  current,
  pageSize,
  onPageChange,
  loading,
  listLength,
  pageSizeOptions = [10, 20, 50, 100],
  onPageSizeChange,
  showQuickJumper,
  flushTop,
}: {
  total: number;
  current: number;
  pageSize: number;
  onPageChange: (page: number) => void;
  loading: boolean;
  listLength: number;
  /** 传入时显示「每页条数」下拉 */
  pageSizeOptions?: number[];
  onPageSizeChange?: (size: number) => void;
  /** 是否显示「前往 x 页」输入框 */
  showQuickJumper?: boolean;
  /** 贴紧表格底部：无上圆角与外侧边框，仅顶部分隔线（用于外层统一列表卡片） */
  flushTop?: boolean;
}) {
  const { t } = useTranslation();
  const totalPages = Math.max(1, Math.ceil(total / pageSize));
  const [jumpVal, setJumpVal] = useState(String(current));
  useEffect(() => {
    setJumpVal(String(current));
  }, [current]);
  if (loading || listLength === 0) return null;
  const extraControls = Boolean(onPageSizeChange || showQuickJumper);
  return (
    <div
      className={
        flushTop
          ? 'border-t border-gray-100/80 bg-slate-50/30 px-6 py-6 sm:px-8 sm:py-8'
          : 'rounded-lg border border-gray-200 bg-white px-6 py-6 sm:py-7'
      }
    >
      <div className={`flex items-center justify-between${extraControls ? ' flex-wrap gap-3' : ''}`}>
        <div className="text-sm text-gray-600">
          {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
        </div>
        <div className="flex items-center gap-2">
          {onPageSizeChange ? (
            <Select
              value={pageSize}
              style={{ width: 110 }}
              options={pageSizeOptions.map((n) => ({ value: n, label: `${n}条/页` }))}
              onChange={(v) => onPageSizeChange(v)}
            />
          ) : null}
          <Button onClick={() => onPageChange(current - 1)} disabled={current <= 1}>
            {t('common.prevPage')}
          </Button>
          <span className="flex items-center px-4 py-2 text-sm text-gray-600">
            {current} / {totalPages}
          </span>
          <Button onClick={() => onPageChange(current + 1)} disabled={current >= totalPages}>
            {t('common.nextPage')}
          </Button>
          {showQuickJumper ? (
            <span className="flex items-center gap-1 text-sm text-gray-600">
              前往
              <Input
                className="w-12 text-center"
                size="small"
                value={jumpVal}
                onChange={(e) => setJumpVal(e.target.value)}
                onPressEnter={() => {
                  const p = parseInt(jumpVal, 10);
                  if (Number.isFinite(p) && p >= 1 && p <= totalPages) onPageChange(p);
                }}
              />
              页
            </span>
          ) : null}
        </div>
      </div>
    </div>
  );
}

const ghostLinkHover = {
  onMouseEnter: (e: React.MouseEvent<HTMLButtonElement>) => {
    e.currentTarget.style.color = '#1677ff';
    e.currentTarget.style.textDecoration = 'underline';
    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
  },
  onMouseLeave: (e: React.MouseEvent<HTMLButtonElement>) => {
    e.currentTarget.style.color = '#000000';
    e.currentTarget.style.textDecoration = 'none';
    e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
  },
};

/** 与列表「查看」一致 */
export function MaterialViewButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <UIButton
      variant="ghost"
      size="sm"
      onClick={onClick}
      className="h-8 px-2 transition-colors hover:underline"
      style={{ color: '#000000' }}
      {...ghostLinkHover}
    >
      <Eye className="w-4 h-4" style={{ color: '#000000' }} />
      <span className="ml-1">{label}</span>
    </UIButton>
  );
}

/** 与点位管理列表「编辑」一致 */
export function MaterialEditButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <UIButton
      variant="ghost"
      size="sm"
      onClick={onClick}
      className="h-8 px-2 transition-colors hover:underline"
      style={{ color: '#000000' }}
      {...ghostLinkHover}
    >
      <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
      <span className="ml-1">{label}</span>
    </UIButton>
  );
}

/** 与点位管理列表「删除」一致 */
export function MaterialDeleteButton({ label, onClick }: { label: string; onClick: () => void }) {
  return (
    <UIButton
      variant="ghost"
      size="sm"
      onClick={onClick}
      className="h-8 px-2 transition-colors hover:underline"
      style={{ color: '#000000' }}
      {...ghostLinkHover}
    >
      <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
      <span className="ml-1">{label}</span>
    </UIButton>
  );
}

/** 与点位管理删除确认弹框一致 */
export function materialConfirmDelete(
  t: (key: string) => string,
  options: { count?: number; onOk: () => void | Promise<void> }
) {
  const count = options.count ?? 1;
  Modal.confirm({
    title: t('common.confirmDelete'),
    icon: <ExclamationCircleOutlined />,
    content: `${t('common.confirmDeleteText')} ${count} ${t('common.records')}?`,
    okText: t('common.confirmDelete'),
    okType: 'danger',
    cancelText: t('common.cancel'),
    onOk: options.onOk,
  });
}

/** 与点位管理表单弹窗一致的 Modal 默认属性（在组件内展开） */
export function getMaterialFormModalProps(t: (key: string) => string, width: number = 720) {
  return {
    okText: t('common.confirm'),
    cancelText: t('common.cancel'),
    width,
    destroyOnClose: true as const,
  };
}

export const materialFormLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
  layout: 'horizontal' as const,
};
