import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Select, Button, Space, Modal, InputNumber, DatePicker, message, Tag } from 'antd';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { getMerchantRooms } from '@/api/room';
import { getRoomCalendar, batchUpdateCalendar, singleDayUpdate } from '@/api/room-calendar';

const { RangePicker } = DatePicker;

const weekDays = ['日', '一', '二', '三', '四', '五', '六'];

const RoomCalendar: React.FC = () => {
  const { roomId: urlRoomId } = useParams();
  const navigate = useNavigate();

  const [roomList, setRoomList] = useState<any[]>([]);
  const [roomId, setRoomId] = useState<number | undefined>(urlRoomId ? Number(urlRoomId) : undefined);
  const [currentMonth, setCurrentMonth] = useState<Dayjs>(dayjs().startOf('month'));
  const [calendarData, setCalendarData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // 单日编辑
  const [editDay, setEditDay] = useState<{ date: string; price: number; stock: number; status: string } | null>(null);
  const [editModalOpen, setEditModalOpen] = useState(false);

  // 批量编辑
  const [batchModalOpen, setBatchModalOpen] = useState(false);
  const [batchRange, setBatchRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [batchPrice, setBatchPrice] = useState<number | null>(null);
  const [batchStock, setBatchStock] = useState<number | null>(null);

  useEffect(() => {
    getMerchantRooms({ page: 1, pageSize: 200 }).then((res: any) => {
      const list = res.data?.list || [];
      setRoomList(list);
      if (!roomId && list.length > 0) {
        setRoomId(list[0].id);
      }
    });
  }, []);

  const monthStart = currentMonth.format('YYYY-MM-DD');
  const monthEnd = currentMonth.endOf('month').format('YYYY-MM-DD');

  const fetchCalendar = useCallback(async () => {
    if (!roomId) return;
    setLoading(true);
    try {
      const res: any = await getRoomCalendar(roomId, monthStart, monthEnd);
      setCalendarData(res.data || []);
    } finally {
      setLoading(false);
    }
  }, [roomId, monthStart, monthEnd]);

  useEffect(() => { fetchCalendar(); }, [fetchCalendar]);

  const calendarDays = useMemo(() => {
    const start = currentMonth.startOf('month');
    const firstDayWeek = start.day();
    const daysInMonth = currentMonth.daysInMonth();
    const today = dayjs().format('YYYY-MM-DD');

    const dataMap = new Map(calendarData.map((d: any) => [d.date, d]));
    const days: (any | null)[] = [];

    for (let i = 0; i < firstDayWeek; i++) days.push(null);

    for (let d = 1; d <= daysInMonth; d++) {
      const dateStr = currentMonth.date(d).format('YYYY-MM-DD');
      const rec = dataMap.get(dateStr);
      days.push({
        day: d,
        date: dateStr,
        price: rec ? rec.price : 0,
        stock: rec ? rec.stock : 0,
        sold: rec ? rec.sold : 0,
        status: rec ? rec.status : 'available',
        initialized: rec ? rec.initialized : false,
        isToday: dateStr === today,
        isPast: dateStr < today,
      });
    }
    return days;
  }, [currentMonth, calendarData]);

  const handleDayClick = (day: any) => {
    if (!day || day.isPast) return;
    setEditDay({ date: day.date, price: day.price, stock: day.stock, status: day.status });
    setEditModalOpen(true);
  };

  const handleSingleSave = async () => {
    if (!roomId || !editDay) return;
    try {
      await singleDayUpdate({ roomId, date: editDay.date, price: editDay.price, stock: editDay.stock, status: editDay.status });
      message.success('更新成功');
      setEditModalOpen(false);
      fetchCalendar();
    } catch (e: any) {
      message.error(e.message || '操作失败');
    }
  };

  const handleBatchSave = async () => {
    if (!roomId || !batchRange) {
      message.warning('请选择日期范围');
      return;
    }
    try {
      const data: any = {
        roomId,
        startDate: batchRange[0].format('YYYY-MM-DD'),
        endDate: batchRange[1].format('YYYY-MM-DD'),
      };
      if (batchPrice !== null) data.price = batchPrice;
      if (batchStock !== null) data.stock = batchStock;
      await batchUpdateCalendar(data);
      message.success('批量设置成功');
      setBatchModalOpen(false);
      setBatchPrice(null);
      setBatchStock(null);
      fetchCalendar();
    } catch (e: any) {
      message.error(e.message || '操作失败');
    }
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Space>
          <h2 style={{ margin: 0 }}>房量房价</h2>
          <Select
            style={{ width: 200 }}
            placeholder="选择房源"
            value={roomId}
            onChange={(v) => setRoomId(v)}
            options={roomList.map((r: any) => ({ label: r.name, value: r.id }))}
          />
        </Space>
        <Space>
          <Button onClick={() => setCurrentMonth(currentMonth.subtract(1, 'month'))}>上月</Button>
          <span style={{ fontWeight: 600, fontSize: 16 }}>{currentMonth.format('YYYY年MM月')}</span>
          <Button onClick={() => setCurrentMonth(currentMonth.add(1, 'month'))}>下月</Button>
          <Button type="primary" onClick={() => setBatchModalOpen(true)}>批量设置</Button>
        </Space>
      </div>

      {/* 星期头 */}
      <div style={{ display: 'flex', background: '#fafafa', borderBottom: '1px solid #f0f0f0', padding: '8px 0' }}>
        {weekDays.map((w) => (
          <div key={w} style={{ flex: 1, textAlign: 'center', fontSize: 14, color: '#999' }}>{w}</div>
        ))}
      </div>

      {/* 日历网格 */}
      <div style={{ display: 'flex', flexWrap: 'wrap', borderLeft: '1px solid #f0f0f0' }}>
        {calendarDays.map((day, i) => (
          <div
            key={i}
            onClick={() => handleDayClick(day)}
            style={{
              width: '14.28%',
              minHeight: 80,
              borderRight: '1px solid #f0f0f0',
              borderBottom: '1px solid #f0f0f0',
              padding: 8,
              cursor: day && !day.isPast ? 'pointer' : 'default',
              background: day?.isToday ? '#fff7e6' : '#fff',
              opacity: day?.isPast ? 0.4 : 1,
            }}
          >
            {day && (
              <>
                <div style={{ fontSize: 14, fontWeight: day.isToday ? 700 : 400, color: day.isToday ? '#FF6B35' : '#333' }}>
                  {day.day}
                </div>
                {day.initialized ? (
                  <>
                    <div style={{ fontSize: 12, color: '#FF6B35', fontWeight: 600 }}>¥{day.price}</div>
                    <Tag color={day.stock > 0 ? 'green' : 'red'} style={{ fontSize: 11, marginTop: 2, padding: '0 4px' }}>
                      余{day.stock}
                    </Tag>
                    {day.status === 'unavailable' && (
                      <Tag color="default" style={{ fontSize: 11, padding: '0 4px' }}>关闭</Tag>
                    )}
                  </>
                ) : (
                  <Tag style={{ fontSize: 11, marginTop: 4 }}>未设</Tag>
                )}
              </>
            )}
          </div>
        ))}
      </div>

      {/* 单日编辑弹窗 */}
      <Modal
        title={`编辑 ${editDay?.date}`}
        open={editModalOpen}
        onOk={handleSingleSave}
        onCancel={() => setEditModalOpen(false)}
        okText="保存"
      >
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>房价 (元/晚)</div>
          <InputNumber
            min={0}
            precision={2}
            value={editDay?.price}
            onChange={(v) => editDay && setEditDay({ ...editDay, price: v ?? 0 })}
            style={{ width: '100%' }}
          />
        </div>
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>库存 (间)</div>
          <InputNumber
            min={0}
            value={editDay?.stock}
            onChange={(v) => editDay && setEditDay({ ...editDay, stock: v ?? 0 })}
            style={{ width: '100%' }}
          />
        </div>
        <div>
          <div style={{ marginBottom: 8 }}>状态</div>
          <Select
            value={editDay?.status}
            onChange={(v) => editDay && setEditDay({ ...editDay, status: v })}
            style={{ width: '100%' }}
            options={[
              { label: '可售', value: 'available' },
              { label: '不可售', value: 'unavailable' },
            ]}
          />
        </div>
      </Modal>

      {/* 批量设置弹窗 */}
      <Modal
        title="批量设置房量房价"
        open={batchModalOpen}
        onOk={handleBatchSave}
        onCancel={() => setBatchModalOpen(false)}
        okText="确认设置"
      >
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>日期范围</div>
          <RangePicker style={{ width: '100%' }} onChange={(dates) => {
            if (dates && dates[0] && dates[1]) {
              setBatchRange([dates[0], dates[1]]);
            } else {
              setBatchRange(null);
            }
          }} />
        </div>
        <div style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>房价 (元/晚) — 不填则不修改</div>
          <InputNumber min={0} precision={2} value={batchPrice} onChange={(v) => setBatchPrice(v)} style={{ width: '100%' }} placeholder="不修改" />
        </div>
        <div>
          <div style={{ marginBottom: 8 }}>库存 (间) — 不填则不修改</div>
          <InputNumber min={0} value={batchStock} onChange={(v) => setBatchStock(v)} style={{ width: '100%' }} placeholder="不修改" />
        </div>
      </Modal>
    </div>
  );
};

export default RoomCalendar;
