import { useState, useEffect, useMemo } from 'react';
import {
  Drawer,
  Form,
  Input,
  DatePicker,
  TimePicker,
  Select,
  Switch,
  Collapse,
  Radio,
  Button,
  Typography,
  Space,
} from 'antd';
import {
  CalendarOutlined,
  ClockCircleOutlined,
  BellOutlined,
  BlockOutlined,
  EnvironmentOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import RecurrenceEditor from './RecurrenceEditor';
import type {
  CalendarLayer,
  PersonalCalendarItem,
  CalendarItemType,
  CalendarVisibility,
  CalendarBusyStatus,
  CalendarShowDetailsTo,
  CalendarRecurrenceRule,
  SeriesEditScope,
} from '@/types/api';

const { TextArea } = Input;
const { Text } = Typography;

const PRESET_COLORS = [
  '#1890ff', '#52c41a', '#fa8c16', '#722ed1', '#eb2f96',
  '#13c2c2', '#f5222d', '#faad14', '#2f54eb', '#a0d911',
];

const ITEM_TYPE_OPTIONS: { value: CalendarItemType; label: string; icon: React.ReactNode }[] = [
  { value: 'EVENT', label: 'Event', icon: <CalendarOutlined /> },
  { value: 'TIME_BLOCK', label: 'Time Block', icon: <BlockOutlined /> },
  { value: 'REMINDER', label: 'Reminder', icon: <BellOutlined /> },
];

export interface CalendarItemFormData {
  layerId: string;
  title: string;
  description?: string;
  date: string;
  startTime: string;
  endTime: string;
  isAllDay: boolean;
  itemType: CalendarItemType;
  location?: string;
  color?: string;
  visibility?: CalendarVisibility | null;
  busyStatus: CalendarBusyStatus;
  showDetailsTo: CalendarShowDetailsTo;
  recurrenceRule?: CalendarRecurrenceRule | null;
  recurrenceEnd?: string | null;
}

interface CalendarItemModalProps {
  open: boolean;
  onCancel: () => void;
  onSave: (data: CalendarItemFormData, scope?: SeriesEditScope) => void;
  onDelete?: () => void;
  item?: PersonalCalendarItem | null;
  defaultDate?: string | null;
  layers: CalendarLayer[];
  loading?: boolean;
}

export default function CalendarItemModal({
  open,
  onCancel,
  onSave,
  onDelete,
  item,
  defaultDate,
  layers,
  loading,
}: CalendarItemModalProps) {
  const [form] = Form.useForm();
  const [itemType, setItemType] = useState<CalendarItemType>('EVENT');
  const [isAllDay, setIsAllDay] = useState(false);
  const [colorOverride, setColorOverride] = useState<string | undefined>(undefined);
  const [recurrenceRule, setRecurrenceRule] = useState<CalendarRecurrenceRule | null>(null);
  const [recurrenceEnd, setRecurrenceEnd] = useState<string | null>(null);
  const [editScope, setEditScope] = useState<SeriesEditScope>('THIS_ONLY');

  const isEditing = !!item;
  const isRecurringEdit = isEditing && !!item?.seriesId;

  const userLayers = useMemo(
    () => layers.filter((l) => l.layerType === 'USER'),
    [layers],
  );

  // Reset form when modal opens
  useEffect(() => {
    if (!open) return;

    if (item) {
      form.setFieldsValue({
        title: item.title ?? '',
        layerId: item.layerId ?? userLayers[0]?.id,
        date: item.date ? dayjs(item.date) : dayjs(),
        startTime: item.startTime ? dayjs(item.startTime, 'HH:mm') : dayjs('09:00', 'HH:mm'),
        endTime: item.endTime ? dayjs(item.endTime, 'HH:mm') : dayjs('10:00', 'HH:mm'),
        description: '',
        location: item.location ?? '',
        visibility: null,
        busyStatus: item.busyStatus ?? 'BUSY',
        showDetailsTo: item.showDetailsTo ?? 'FRIENDS',
      });
      setItemType(item.itemType ?? 'EVENT');
      setIsAllDay(item.isAllDay ?? false);
      setColorOverride(item.color !== '#1890ff' ? item.color : undefined);
      setRecurrenceRule(null);
      setRecurrenceEnd(null);
    } else {
      form.resetFields();
      const date = defaultDate ? dayjs(defaultDate) : dayjs();
      form.setFieldsValue({
        date,
        startTime: dayjs('09:00', 'HH:mm'),
        endTime: dayjs('10:00', 'HH:mm'),
        layerId: userLayers[0]?.id,
        busyStatus: 'BUSY',
        showDetailsTo: 'FRIENDS',
        visibility: null,
      });
      setItemType('EVENT');
      setIsAllDay(false);
      setColorOverride(undefined);
      setRecurrenceRule(null);
      setRecurrenceEnd(null);
    }
    setEditScope('THIS_ONLY');
  }, [open, item, defaultDate, userLayers, form]);

  const handleFinish = (values: Record<string, unknown>) => {
    const data: CalendarItemFormData = {
      layerId: values.layerId as string,
      title: values.title as string,
      description: (values.description as string) || undefined,
      date: (values.date as dayjs.Dayjs).format('YYYY-MM-DD'),
      startTime: isAllDay ? '00:00' : (values.startTime as dayjs.Dayjs).format('HH:mm'),
      endTime: isAllDay ? '23:59' : (values.endTime as dayjs.Dayjs).format('HH:mm'),
      isAllDay,
      itemType,
      location: (values.location as string) || undefined,
      color: colorOverride,
      visibility: (values.visibility as CalendarVisibility | null) ?? null,
      busyStatus: (values.busyStatus as CalendarBusyStatus) ?? 'BUSY',
      showDetailsTo: (values.showDetailsTo as CalendarShowDetailsTo) ?? 'FRIENDS',
      recurrenceRule: recurrenceRule ?? undefined,
      recurrenceEnd: recurrenceEnd ?? undefined,
    };

    onSave(data, isRecurringEdit ? editScope : undefined);
  };

  return (
    <Drawer
      open={open}
      onClose={onCancel}
      title={isEditing ? 'Edit Calendar Item' : 'New Calendar Item'}
      width={520}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
      extra={
        <Button type="primary" onClick={() => form.submit()} loading={loading}>
          {isEditing ? 'Save Changes' : 'Create'}
        </Button>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFinish}
        style={{ marginTop: 16 }}
      >
        {/* Item type selector */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
          {ITEM_TYPE_OPTIONS.map((opt) => {
            const selected = itemType === opt.value;
            return (
              <div
                key={opt.value}
                onClick={() => setItemType(opt.value)}
                style={{
                  flex: 1,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 6,
                  padding: '8px 12px',
                  borderRadius: 8,
                  cursor: 'pointer',
                  userSelect: 'none',
                  fontSize: 13,
                  fontWeight: selected ? 600 : 400,
                  background: selected ? 'rgba(24, 144, 255, 0.15)' : 'rgba(255,255,255,0.04)',
                  border: selected
                    ? '1px solid rgba(24, 144, 255, 0.4)'
                    : '1px solid rgba(255,255,255,0.1)',
                  color: selected ? '#1890ff' : 'rgba(255,255,255,0.65)',
                  transition: 'all 0.2s',
                }}
              >
                {opt.icon}
                {opt.label}
              </div>
            );
          })}
        </div>

        <Form.Item
          name="title"
          rules={[{ required: true, message: 'Title is required' }]}
        >
          <Input
            placeholder={
              itemType === 'REMINDER'
                ? 'Reminder title...'
                : itemType === 'TIME_BLOCK'
                  ? 'Block title (e.g. "Focus time")...'
                  : 'Event title...'
            }
            size="large"
            style={{ fontSize: 16 }}
          />
        </Form.Item>

        <Form.Item
          name="layerId"
          label="Layer"
          rules={[{ required: true, message: 'Select a layer' }]}
        >
          <Select
            options={userLayers.map((l) => ({
              value: l.id,
              label: (
                <Space>
                  <span
                    style={{
                      width: 10,
                      height: 10,
                      borderRadius: '50%',
                      background: l.color,
                      display: 'inline-block',
                    }}
                  />
                  {l.name}
                </Space>
              ),
            }))}
            placeholder="Select layer"
          />
        </Form.Item>

        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <Form.Item
            name="date"
            label="Date"
            rules={[{ required: true, message: 'Required' }]}
            style={{ flex: 1 }}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label=" " style={{ paddingTop: 4 }}>
            <Space>
              <Switch
                checked={isAllDay}
                onChange={setIsAllDay}
                size="small"
              />
              <Text style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)' }}>All day</Text>
            </Space>
          </Form.Item>
        </div>

        {!isAllDay && (
          <div style={{ display: 'flex', gap: 12 }}>
            <Form.Item
              name="startTime"
              label="Start"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <TimePicker format="HH:mm" minuteStep={5} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              name="endTime"
              label="End"
              rules={[{ required: true, message: 'Required' }]}
              style={{ flex: 1 }}
            >
              <TimePicker format="HH:mm" minuteStep={5} style={{ width: '100%' }} />
            </Form.Item>
          </div>
        )}

        {itemType === 'EVENT' && (
          <Form.Item name="location" label="Location">
            <Input prefix={<EnvironmentOutlined />} placeholder="Optional location" />
          </Form.Item>
        )}

        <Form.Item name="description" label="Description">
          <TextArea rows={2} placeholder="Optional description" />
        </Form.Item>

        {/* Time block specific fields */}
        {itemType === 'TIME_BLOCK' && (
          <div style={{ display: 'flex', gap: 12 }}>
            <Form.Item name="busyStatus" label="Status" style={{ flex: 1 }}>
              <Select
                options={[
                  { value: 'BUSY', label: 'Busy' },
                  { value: 'TENTATIVE', label: 'Tentative' },
                  { value: 'FREE', label: 'Free' },
                ]}
              />
            </Form.Item>
            <Form.Item name="showDetailsTo" label="Show details to" style={{ flex: 1 }}>
              <Select
                options={[
                  { value: 'NOBODY', label: 'Nobody' },
                  { value: 'FRIENDS', label: 'Friends' },
                  { value: 'EVERYONE', label: 'Everyone' },
                ]}
              />
            </Form.Item>
          </div>
        )}

        {/* Visibility override */}
        <Form.Item name="visibility" label="Visibility override">
          <Select
            allowClear
            placeholder="Inherit from layer"
            options={[
              { value: 'PRIVATE', label: 'Private' },
              { value: 'FRIENDS', label: 'Friends only' },
              { value: 'PUBLIC', label: 'Public' },
            ]}
          />
        </Form.Item>

        {/* Color override */}
        <div style={{ marginBottom: 16 }}>
          <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 6 }}>
            Color override
          </Text>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <div
              onClick={() => setColorOverride(undefined)}
              style={{
                width: 24,
                height: 24,
                borderRadius: '50%',
                background: 'rgba(255,255,255,0.08)',
                cursor: 'pointer',
                border: !colorOverride ? '2px solid #1890ff' : '2px solid transparent',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 10,
                color: 'rgba(255,255,255,0.45)',
              }}
              title="Use layer color"
            >
              Auto
            </div>
            {PRESET_COLORS.map((c) => (
              <div
                key={c}
                onClick={() => setColorOverride(c)}
                style={{
                  width: 24,
                  height: 24,
                  borderRadius: '50%',
                  background: c,
                  cursor: 'pointer',
                  border: colorOverride === c ? '2px solid #fff' : '2px solid transparent',
                }}
              />
            ))}
          </div>
        </div>

        {/* Recurrence */}
        <Collapse
          ghost
          items={[
            {
              key: 'recurrence',
              label: (
                <Text style={{ fontSize: 13, color: 'rgba(255,255,255,0.65)' }}>
                  <ClockCircleOutlined style={{ marginRight: 6 }} />
                  Recurrence
                  {recurrenceRule && (
                    <span style={{ color: '#1890ff', marginLeft: 8, fontSize: 12 }}>
                      (configured)
                    </span>
                  )}
                </Text>
              ),
              children: (
                <RecurrenceEditor
                  value={recurrenceRule}
                  endDate={recurrenceEnd}
                  onChange={(rule, end) => {
                    setRecurrenceRule(rule);
                    setRecurrenceEnd(end);
                  }}
                />
              ),
            },
          ]}
          style={{ marginBottom: 16, background: 'rgba(255,255,255,0.02)', borderRadius: 8 }}
        />

        {/* Edit scope for recurring items */}
        {isRecurringEdit && (
          <div
            style={{
              marginBottom: 16,
              padding: 12,
              background: 'rgba(250, 140, 22, 0.08)',
              border: '1px solid rgba(250, 140, 22, 0.2)',
              borderRadius: 8,
            }}
          >
            <Text style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)', display: 'block', marginBottom: 8 }}>
              This is a recurring event. Apply changes to:
            </Text>
            <Radio.Group
              value={editScope}
              onChange={(e) => setEditScope(e.target.value)}
            >
              <Space direction="vertical" size={4}>
                <Radio value="THIS_ONLY">This event only</Radio>
                <Radio value="THIS_AND_FUTURE">This and future events</Radio>
                <Radio value="ALL">All events in the series</Radio>
              </Space>
            </Radio.Group>
          </div>
        )}

        {/* Actions */}
        {isEditing && onDelete && (
          <div style={{ marginTop: 8 }}>
            <Button
              danger
              icon={<DeleteOutlined />}
              onClick={onDelete}
            >
              Delete
            </Button>
          </div>
        )}
      </Form>
    </Drawer>
  );
}
