import { useMemo, useState } from 'react';
import { Button, Dropdown, Input, Popover, Space, Table, Tag } from 'antd';
import type { TableColumnsType } from 'antd';
import { DeleteOutlined, EditOutlined, FilterOutlined, MoreOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import AppBreadcrumb from '@/components/AppBreadcrumb';
import AppActionBar from '@/components/common/AppActionBar';
import AppSearchBar from '@/components/common/AppSearchBar';

// ─────────────────────────────────────────────────────────────────────────────
// List management screen — the house recipe, ready to adapt.
//   breadcrumb → action bar → search bar → table (row-select, status badge, pagination, row menu)
// Replace `Row`, `DATA`, the columns, and the handlers with your entity's real data/services.
// ─────────────────────────────────────────────────────────────────────────────

interface Row {
  id: string;
  code: string;
  name: string;
  status: string;
  updated: string;
}

const DATA: Row[] = [
  { id: '1', code: 'CURRENCY.USD', name: 'US Dollar', status: 'ACTIVE', updated: '2026-06-30' },
  { id: '2', code: 'CURRENCY.VND', name: 'Vietnamese Dong', status: 'ACTIVE', updated: '2026-06-28' },
  { id: '3', code: 'UNIT.KG', name: 'Kilogram', status: 'DRAFT', updated: '2026-06-21' },
  { id: '4', code: 'UNIT.LEGACY', name: 'Deprecated unit', status: 'REJECTED', updated: '2026-05-11' },
];

// Map a status string to a badge colour class. Keep this identical across modules.
const statusClass = (status: string) => {
  const s = String(status || '').toUpperCase();
  if (['PENDING', 'UNDONE', 'VALIDATING', 'DRAFT', 'INACTIVE'].includes(s)) return 'badge-pending';
  if (['APPROVED', 'VALIDATED_SUCCESSFUL'].includes(s)) return 'badge-info';
  if (['ACTIVE', 'SUBMITTED'].includes(s)) return 'badge-success';
  if (['REJECTED', 'VALIDATED_FAILED', 'FAILED'].includes(s)) return 'badge-error';
  return 'badge-warning';
};

const BREADCRUMB = [{ label: 'Reference' }, { label: 'Currencies' }];

const ListManagementScreen = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [keyword, setKeyword] = useState('');

  const rows = useMemo(() => DATA.filter((r) => r.code.toLowerCase().includes(keyword.toLowerCase()) || r.name.toLowerCase().includes(keyword.toLowerCase())), [keyword]);

  const columns: TableColumnsType<Row> = [
    { title: 'Code', dataIndex: 'code', width: 180 },
    { title: 'Name', dataIndex: 'name' },
    {
      title: 'Status',
      dataIndex: 'status',
      width: 120,
      render: (status: string) => <span className={`${statusClass(status)} badge-rvn`}>{status}</span>,
    },
    { title: 'Updated', dataIndex: 'updated', width: 120 },
    {
      key: 'action',
      title: '',
      width: 44,
      fixed: 'right',
      render: (_text, row) => (
        <Dropdown
          trigger={['click']}
          menu={{
            items: [
              { key: 'edit', label: <span><EditOutlined /> Edit</span>, onClick: () => onEdit(row) },
              { key: 'delete', label: <span><DeleteOutlined /> Delete</span>, danger: true, onClick: () => onDelete([row.id]) },
            ],
          }}
        >
          <Button type="text" size="small" icon={<MoreOutlined style={{ fontSize: 18 }} />} />
        </Dropdown>
      ),
    },
  ];

  const onCreate = () => {/* navigate to the create page */};
  const onEdit = (row: Row) => {/* navigate to `/edit/${row.id}` */ void row;};
  const onDelete = (ids: React.Key[]) => {/* call the delete service, then refresh */ void ids;};
  const onRefresh = () => {/* re-fetch */};

  return (
    <div className="w-100">
      <AppBreadcrumb items={BREADCRUMB} />

      <AppActionBar>
        <Space size={10}>
          <Button size="small" icon={<PlusOutlined />} onClick={onCreate}>Create</Button>
          <Button size="small" icon={<ReloadOutlined />} onClick={onRefresh}>Refresh</Button>
        </Space>
        <Button size="small" danger icon={<DeleteOutlined />} disabled={!selectedRowKeys.length} onClick={() => onDelete(selectedRowKeys)}>
          Delete{selectedRowKeys.length ? ` (${selectedRowKeys.length})` : ''}
        </Button>
      </AppActionBar>

      <AppSearchBar
        search={
          <Input
            placeholder="Search code or name..."
            prefix={<SearchOutlined />}
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            allowClear
            style={{ minWidth: 280, maxWidth: 520 }}
          />
        }
        addFilter={
          <Dropdown menu={{ items: [{ key: 'status', label: 'Status' }] }}>
            <Button icon={<FilterOutlined />}>Add filters</Button>
          </Dropdown>
        }
      >
        <Popover trigger="click" content={<div style={{ minWidth: 200 }}>Status filter editor…</div>}>
          <Tag closable>status: ACTIVE</Tag>
        </Popover>
      </AppSearchBar>

      <Table
        size="small"
        rowKey="id"
        columns={columns}
        dataSource={rows}
        rowSelection={{ selectedRowKeys, onChange: setSelectedRowKeys }}
        onRow={(record) => ({ onDoubleClick: () => onEdit(record) })}
        pagination={{
          current: 1,
          pageSize: 10,
          total: rows.length,
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
          pageSizeOptions: ['10', '20', '50', '100'],
        }}
      />
    </div>
  );
};

export default ListManagementScreen;
