import React from 'react';
import { Badge, Button, Popconfirm, Space, Tag } from 'antd';
import { InboxOutlined, UndoOutlined } from '@ant-design/icons';
import PermissionButton from '../../components/PermissionButton';
import EditableCell from '../../components/EditableCell';

export const statusMap: Record<string, { text: string; color: string }> = {
  available: { text: '可入住', color: 'green' },
  full: { text: '已满', color: 'red' },
  maintenance: { text: '维修中', color: 'orange' },
  archived: { text: '已归档', color: '#999' },
};

export const ROOM_STATUS_OPTIONS = [
  { value: 'available', label: '可入住' },
  { value: 'full', label: '已满' },
  { value: 'maintenance', label: '维修中' },
];

export const RENTAL_CATEGORY_OPTIONS = [
  { value: 'long', label: '长租' },
  { value: 'short', label: '短租' },
];

export const BED_STATUS_OPTIONS = [
  { value: 'available', label: '空闲' },
  { value: 'occupied', label: '占用' },
  { value: 'maintenance', label: '维修' },
];

export const BED_STATUS_MAP: Record<string, { text: string; color: string }> = {
  available: { text: '空闲', color: 'green' },
  occupied: { text: '占用', color: 'blue' },
  maintenance: { text: '维修', color: 'orange' },
};

export interface BedItem {
  id: number;
  bedNumber: string;
  status: string;
  notes?: string | null;
}

export interface LockerItem {
  id: number;
  lockerNumber: string;
  status: string;
  notes?: string | null;
}

export function parseRoomNumber(input: string) {
  const match = /^(\d+)-(\d+)/.exec(input.trim());
  if (!match) return null;
  return {
    building: `${match[1]}号楼`,
    floor: Number(match[2]),
    roomType: input.includes('单人') ? '单人间' : input.includes('家庭') ? '家庭房' : '四人间',
  };
}

export const EditableRoomCell = <R extends { id: number }>({
  value,
  field,
  record,
  editor,
  min,
  max,
  required,
  options,
  archived = false,
  onSave,
  children,
}: {
  value: unknown;
  field: string;
  record: R;
  editor?: React.ComponentProps<typeof EditableCell>['editor'];
  min?: number;
  max?: number;
  required?: boolean;
  options?: Array<{ value: string; label: string }>;
  archived?: boolean;
  onSave: (record: R, field: string, value: unknown) => Promise<void> | void;
  children?: React.ReactNode;
}) => (
  <EditableCell
    value={value}
    editor={editor}
    min={min}
    max={max}
    required={required}
    options={options}
    permission="room:edit"
    disabled={archived}
    onSave={async (next) => {
      await onSave(record, field, next);
    }}
  >
    {children ?? String(value ?? '-')}
  </EditableCell>
);

export interface RoomColumnContext {
  canEditRooms: boolean;
  canDeleteRooms: boolean;
  canPurgeRooms: boolean;
  onSaveRoomCell: (record: any, field: string, value: unknown) => Promise<void> | void;
  onRestore: (id: number) => Promise<unknown> | unknown;
  onArchive: (id: number) => Promise<unknown> | unknown;
  onPurge: (id: number, name: string) => void;
  onView: (record: any) => void;
  onEdit: (record: any) => void;
}

function buildRoomIdentityColumns(ctx: RoomColumnContext) {
  const { onSaveRoomCell } = ctx;
  return [
    {
      title: '房间号',
      dataIndex: 'roomNumber',
      width: 100,
      sorter: (a: any, b: any) => a.roomNumber.localeCompare(b.roomNumber),
      render: (v: string, r: any) => (
        <EditableRoomCell value={v} field="roomNumber" record={r} required onSave={onSaveRoomCell}>
          {v}
        </EditableRoomCell>
      ),
    },
    {
      title: '楼栋',
      dataIndex: 'building',
      width: 80,
      render: (v: string, r: any) => (
        <EditableRoomCell value={v} field="building" record={r} onSave={onSaveRoomCell}>
          {v || '-'}
        </EditableRoomCell>
      ),
    },
    {
      title: '楼层',
      dataIndex: 'floor',
      width: 80,
      render: (v: number, r: any) => (
        <EditableRoomCell value={v} field="floor" record={r} editor="number" onSave={onSaveRoomCell}>
          {v ?? '-'}
        </EditableRoomCell>
      ),
    },
    {
      title: '类型',
      dataIndex: 'roomType',
      width: 90,
      render: (v: any, r: any) => (
        <EditableRoomCell value={v} field="roomType" record={r} onSave={onSaveRoomCell}>
          {v || '-'}
        </EditableRoomCell>
      ),
    },
    {
      title: '租赁类型',
      dataIndex: 'rentalCategory',
      width: 100,
      render: (v: string, r: any) => (
        <EditableRoomCell
          value={v}
          field="rentalCategory"
          record={r}
          editor="select"
          options={RENTAL_CATEGORY_OPTIONS}
          onSave={onSaveRoomCell}
        >
          {v === 'long' ? (
            <Tag color="blue">长租</Tag>
          ) : v === 'short' ? (
            <Tag color="green">短租</Tag>
          ) : (
            '-'
          )}
        </EditableRoomCell>
      ),
    },
    {
      title: '月租金',
      dataIndex: 'monthlyRate',
      width: 100,
      render: (v: number, r: any) => (
        <EditableRoomCell value={v} field="monthlyRate" record={r} editor="money" min={0} onSave={onSaveRoomCell}>
          {v ? `¥${v}` : '-'}
        </EditableRoomCell>
      ),
    },
  ];
}

function buildRoomStatusColumns(ctx: RoomColumnContext) {
  const { onSaveRoomCell } = ctx;
  return [
    {
      title: '额定人数',
      dataIndex: 'capacity',
      width: 80,
      render: (v: number, r: any) => (
        <EditableRoomCell value={v} field="capacity" record={r} editor="number" min={1} required onSave={onSaveRoomCell}>
          {v}
        </EditableRoomCell>
      ),
    },
    {
      title: '当前入住',
      width: 80,
      render: (_: any, r: any) =>
        r.status === 'archived' ? (
          <Tag color="#999">-</Tag>
        ) : (
          <Badge
            count={r.currentCount}
            showZero
            overflowCount={99}
            style={{ backgroundColor: r.currentCount >= r.capacity ? '#ff4d4f' : '#52c41a' }}
          />
        ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (s: string, r: any) => (
        <EditableRoomCell
          value={s}
          field="status"
          record={r}
          editor="select"
          options={ROOM_STATUS_OPTIONS}
          onSave={onSaveRoomCell}
        >
          <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag>
        </EditableRoomCell>
      ),
    },
  ];
}

function buildRoomActionColumn(ctx: RoomColumnContext) {
  const {
    canEditRooms,
    canDeleteRooms,
    canPurgeRooms,
    onRestore,
    onArchive,
    onPurge,
    onView,
    onEdit,
  } = ctx;
  return {
    title: '操作',
    width: 220,
    render: (_: unknown, record: unknown) => {
      const r = record as { status?: string; id: number; roomNumber?: string };
      return (
        <Space>
          {r.status === 'archived' ? (
            <>
              {canEditRooms ? (
                <Popconfirm title="确定恢复此宿舍？" onConfirm={() => onRestore(r.id)}>
                  <Button size="small" icon={<UndoOutlined />} type="link">
                    恢复
                  </Button>
                </Popconfirm>
              ) : null}
              {canPurgeRooms ? (
                <Button
                  size="small"
                  danger
                  type="link"
                  onClick={() => onPurge(r.id, r.roomNumber ?? '')}
                >
                  删除
                </Button>
              ) : null}
            </>
          ) : (
            <>
              <PermissionButton
                permission="room:view"
                size="small"
                type="link"
                onClick={() => onView(record)}
              >
                查看
              </PermissionButton>
              <PermissionButton
                permission="room:edit"
                size="small"
                onClick={() => onEdit(record)}
              >
                编辑
              </PermissionButton>
              {canDeleteRooms ? (
                <Popconfirm title="确定归档？" onConfirm={() => onArchive(r.id)}>
                  <Button size="small" icon={<InboxOutlined />}>
                    归档
                  </Button>
                </Popconfirm>
              ) : null}
            </>
          )}
        </Space>
      );
    },
  };
}

export function buildRoomColumns(ctx: RoomColumnContext) {
  return [
    ...buildRoomIdentityColumns(ctx),
    ...buildRoomStatusColumns(ctx),
    buildRoomActionColumn(ctx),
  ];
}

export function useRoomColumns(ctx: RoomColumnContext) {
  return React.useMemo(() => buildRoomColumns(ctx), [ctx]);
}
