import { useState, useEffect, useCallback } from 'react';
import {
  DatePicker,
  Select,
  Space,
  Typography,
  Skeleton,
  Empty,
  Tooltip,
  theme,
} from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import { api } from '@/lib/api';
import type { AvailabilityResponse } from '@/types/api';

const { Text } = Typography;
const { RangePicker } = DatePicker;

interface AvailabilityFinderProps {
  viewId: string;
  onSlotClick?: (date: string, time: string) => void;
}

const DURATION_OPTIONS = [
  { value: 15, label: '15 min' },
  { value: 30, label: '30 min' },
  { value: 60, label: '1 hour' },
];

export default function AvailabilityFinder({ viewId, onSlotClick }: AvailabilityFinderProps) {
  const { token } = theme.useToken();

  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs(),
    dayjs().add(6, 'day'),
  ]);
  const [dayStart, setDayStart] = useState(9);
  const [dayEnd, setDayEnd] = useState(18);
  const [slotDuration, setSlotDuration] = useState(30);
  const [availability, setAvailability] = useState<AvailabilityResponse | null>(null);
  const [loading, setLoading] = useState(false);

  const hourOptions = Array.from({ length: 24 }, (_, i) => ({
    value: i,
    label: `${String(i).padStart(2, '0')}:00`,
  }));

  const fetchAvailability = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<AvailabilityResponse>(
        `/calendar/shared/${viewId}/availability`,
        {
          params: {
            startDate: dateRange[0].format('YYYY-MM-DD'),
            endDate: dateRange[1].format('YYYY-MM-DD'),
            dayStart,
            dayEnd,
            slotMinutes: slotDuration,
          },
        },
      );
      setAvailability(data);
    } catch {
      setAvailability(null);
    } finally {
      setLoading(false);
    }
  }, [viewId, dateRange, dayStart, dayEnd, slotDuration]);

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

  // Build time slots
  const timeSlots: string[] = [];
  for (let h = dayStart; h < dayEnd; h++) {
    for (let m = 0; m < 60; m += slotDuration) {
      if (h === dayEnd - 1 && m + slotDuration > 60) break;
      timeSlots.push(`${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`);
    }
  }

  // Build date columns
  const dates: string[] = [];
  let d = dateRange[0];
  while (d.isBefore(dateRange[1]) || d.isSame(dateRange[1], 'day')) {
    dates.push(d.format('YYYY-MM-DD'));
    d = d.add(1, 'day');
  }

  const statusColors: Record<string, string> = {
    free: '#52c41a',
    busy: '#ff4d4f',
    tentative: '#faad14',
  };

  return (
    <div>
      <Text strong style={{ fontSize: 14, display: 'block', marginBottom: 12 }}>
        Find Availability
      </Text>

      <Space wrap style={{ marginBottom: 12 }}>
        <RangePicker
          size="small"
          value={dateRange}
          onChange={(vals) => {
            if (vals && vals[0] && vals[1]) {
              setDateRange([vals[0], vals[1]]);
            }
          }}
        />
        <Select
          size="small"
          value={dayStart}
          options={hourOptions}
          onChange={setDayStart}
          style={{ width: 90 }}
          placeholder="Start"
        />
        <Select
          size="small"
          value={dayEnd}
          options={hourOptions}
          onChange={setDayEnd}
          style={{ width: 90 }}
          placeholder="End"
        />
        <Select
          size="small"
          value={slotDuration}
          options={DURATION_OPTIONS}
          onChange={setSlotDuration}
          style={{ width: 90 }}
        />
      </Space>

      {loading ? (
        <Skeleton active paragraph={{ rows: 6 }} />
      ) : !availability || dates.length === 0 ? (
        <Empty description="Select a date range" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ borderCollapse: 'collapse', width: '100%', fontSize: 11 }}>
            <thead>
              <tr>
                <th
                  style={{
                    padding: '4px 8px',
                    borderBottom: `1px solid ${token.colorBorderSecondary}`,
                    position: 'sticky',
                    left: 0,
                    background: token.colorBgContainer,
                    zIndex: 1,
                  }}
                />
                {dates.map((date) => (
                  <th
                    key={date}
                    style={{
                      padding: '4px 8px',
                      borderBottom: `1px solid ${token.colorBorderSecondary}`,
                      whiteSpace: 'nowrap',
                      fontWeight: 500,
                    }}
                  >
                    {dayjs(date).format('ddd M/D')}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {timeSlots.map((time) => (
                <tr key={time}>
                  <td
                    style={{
                      padding: '3px 8px',
                      borderRight: `1px solid ${token.colorBorderSecondary}`,
                      whiteSpace: 'nowrap',
                      position: 'sticky',
                      left: 0,
                      background: token.colorBgContainer,
                      zIndex: 1,
                      color: 'rgba(255,255,255,0.6)',
                    }}
                  >
                    {time}
                  </td>
                  {dates.map((date) => {
                    const dayData = availability.dates[date];
                    const slot = dayData?.slots.find((s) => s.time === time);
                    const allFree = slot?.allFree;

                    return (
                      <td
                        key={date}
                        onClick={() => allFree && onSlotClick?.(date, time)}
                        style={{
                          padding: '3px 6px',
                          border: `1px solid ${token.colorBorderSecondary}`,
                          background: allFree
                            ? 'rgba(82, 196, 26, 0.15)'
                            : 'transparent',
                          cursor: allFree ? 'pointer' : 'default',
                          textAlign: 'center',
                        }}
                      >
                        {slot && (
                          <Space size={2}>
                            {slot.members.map((m) => (
                              <Tooltip key={m.userId} title={`${m.userName}: ${m.status}`}>
                                <div
                                  style={{
                                    width: 8,
                                    height: 8,
                                    borderRadius: '50%',
                                    background: statusColors[m.status] || '#999',
                                    display: 'inline-block',
                                  }}
                                />
                              </Tooltip>
                            ))}
                          </Space>
                        )}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>

          <Space style={{ marginTop: 8 }}>
            <Space size={4}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#52c41a' }} />
              <Text style={{ fontSize: 11 }}>Free</Text>
            </Space>
            <Space size={4}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#ff4d4f' }} />
              <Text style={{ fontSize: 11 }}>Busy</Text>
            </Space>
            <Space size={4}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#faad14' }} />
              <Text style={{ fontSize: 11 }}>Tentative</Text>
            </Space>
          </Space>
        </div>
      )}
    </div>
  );
}
