import { useRef, useState, useEffect, useCallback } from 'react';
import {
  Typography,
  Space,
  Button,
  Table,
  Drawer,
  Form,
  Input,
  Select,
  Tag,
  Popconfirm,
  message,
} from 'antd';
import {
  CalendarOutlined,
  TeamOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import UnifiedCalendar from '@/components/calendar/UnifiedCalendar';
import { api } from '@/lib/api';
import { useMobile } from '@/hooks/useMobile';
import type { UnifiedCalendarItem, AdminCalendarView } from '@/types/api';
import { useNavigate } from 'react-router-dom';
import { ROLE_COLORS, ROLE_OPTIONS } from '@/utils/role-constants';

const { Title, Text } = Typography;

const VIEWS_PANEL_WIDTH = 480;
const FORM_PANEL_WIDTH = 380;

const LAYER_TYPE_OPTIONS = [
  { label: 'Shifts', value: 'SHIFTS' },
  { label: 'Tickets', value: 'TICKETS' },
  { label: 'Polls', value: 'POLLS' },
  { label: 'Public Events', value: 'PUBLIC_EVENTS' },
];

export default function SchedulingCalendarPage() {
  const navigate = useNavigate();
  const { isMobile } = useMobile();
  const addEventRef = useRef<(() => void) | null>(null);

  // Panel state
  const [viewsOpen, setViewsOpen] = useState(false);
  const [formOpen, setFormOpen] = useState(false);

  // Calendar Views state
  const [views, setViews] = useState<AdminCalendarView[]>([]);
  const [viewsLoading, setViewsLoading] = useState(false);
  const [editingView, setEditingView] = useState<AdminCalendarView | null>(null);
  const [saving, setSaving] = useState(false);
  const [form] = Form.useForm();

  const handleShiftClick = (item: UnifiedCalendarItem) => {
    if (item.shiftId) {
      navigate('/app/map/shifts');
    }
  };

  const fetchViews = useCallback(async () => {
    setViewsLoading(true);
    try {
      const { data } = await api.get<{ views: AdminCalendarView[] }>('/admin/calendar/shared');
      setViews(data.views);
    } catch {
      message.error('Failed to load calendar views');
    } finally {
      setViewsLoading(false);
    }
  }, []);

  useEffect(() => {
    if (viewsOpen) fetchViews();
  }, [viewsOpen, fetchViews]);

  const openCreate = () => {
    setEditingView(null);
    form.resetFields();
    setFormOpen(true);
  };

  const openEdit = (view: AdminCalendarView) => {
    setEditingView(view);
    form.setFieldsValue({
      name: view.name,
      description: view.description,
      autoIncludeRoles: view.autoIncludeRoles,
      includedLayerTypes: view.includedLayerTypes,
    });
    setFormOpen(true);
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSaving(true);
      if (editingView) {
        await api.patch(`/admin/calendar/shared/${editingView.id}`, values);
        message.success('View updated');
      } else {
        await api.post('/admin/calendar/shared', values);
        message.success('View created');
      }
      setFormOpen(false);
      fetchViews();
    } catch {
      // validation or API error
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await api.delete(`/admin/calendar/shared/${id}`);
      message.success('View deleted');
      fetchViews();
    } catch {
      message.error('Failed to delete view');
    }
  };

  const closeViews = () => {
    setFormOpen(false);
    setViewsOpen(false);
  };

  const viewColumns = [
    { title: 'Name', dataIndex: 'name', key: 'name' },
    {
      title: 'Roles',
      dataIndex: 'autoIncludeRoles',
      key: 'roles',
      render: (roles: string[]) => (
        <Space size={4} wrap>
          {roles.map((r) => <Tag key={r} color={ROLE_COLORS[r] || 'default'}>{r}</Tag>)}
        </Space>
      ),
    },
    {
      title: 'Layers',
      dataIndex: 'includedLayerTypes',
      key: 'layerTypes',
      render: (types: string[]) => (
        <Space size={4} wrap>
          {types.map((t) => <Tag key={t}>{t}</Tag>)}
        </Space>
      ),
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 100,
      responsive: ['md'] as any,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    },
    {
      title: '',
      key: 'actions',
      width: 80,
      render: (_: unknown, record: AdminCalendarView) => (
        <Space size={4}>
          <Button type="text" size="small" icon={<EditOutlined />} onClick={(e) => { e.stopPropagation(); openEdit(record); }} />
          <Popconfirm title="Delete this view?" onConfirm={() => handleDelete(record.id)} onCancel={(e) => e?.stopPropagation()}>
            <Button type="text" size="small" danger icon={<DeleteOutlined />} onClick={(e) => e.stopPropagation()} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // Compute right margin to squish calendar when drawers are open (skip on mobile — drawers overlay)
  const viewsWidth = isMobile ? '100%' : VIEWS_PANEL_WIDTH;
  const formWidth = isMobile ? '100%' : FORM_PANEL_WIDTH;
  const drawerOffset = isMobile ? 0 : (viewsOpen ? VIEWS_PANEL_WIDTH : 0) + (formOpen ? FORM_PANEL_WIDTH : 0);

  const DRAWER_ROOT = { position: 'absolute' as const, top: 64, height: 'calc(100vh - 64px)' };

  return (
    <div
      style={{
        transition: 'margin-right 0.3s ease',
        marginRight: drawerOffset,
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16, flexWrap: 'wrap', gap: 8 }}>
        <Title level={3} style={{ margin: 0 }}>
          <CalendarOutlined style={{ marginRight: 8 }} />
          Scheduling Calendar
        </Title>

        <Space size={12} wrap>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#1890ff' }} />
            <Text type="secondary" style={{ fontSize: 13 }}>Shifts</Text>
          </Space>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#fa8c16' }} />
            <Text type="secondary" style={{ fontSize: 13 }}>Polls</Text>
          </Space>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#722ed1' }} />
            <Text type="secondary" style={{ fontSize: 13 }}>Ticketed Events</Text>
          </Space>
          <Space size={4}>
            <div style={{ width: 12, height: 12, borderRadius: 2, background: '#52c41a' }} />
            <Text type="secondary" style={{ fontSize: 13 }}>Community Events</Text>
          </Space>

          <Button
            icon={<TeamOutlined />}
            type={viewsOpen ? 'primary' : 'default'}
            onClick={() => viewsOpen ? closeViews() : setViewsOpen(true)}
          >
            {!isMobile && 'Shared Views'}
          </Button>
        </Space>
      </div>

      <UnifiedCalendar
        onShiftSignup={handleShiftClick}
        onAddEvent={addEventRef}
      />

      {/* Shared Views list drawer — shifts left when form drawer opens */}
      <Drawer
        title="Shared Calendar Views"
        open={viewsOpen}
        onClose={closeViews}
        mask={false}
        width={viewsWidth}
        rootStyle={DRAWER_ROOT}
        destroyOnHidden
        styles={{
          wrapper: {
            transition: 'transform 0.3s ease, width 0.3s ease',
            transform: formOpen && !isMobile ? `translateX(-${FORM_PANEL_WIDTH}px)` : undefined,
          },
        }}
        extra={
          <Button type="primary" size="small" icon={<PlusOutlined />} onClick={openCreate}>
            Create View
          </Button>
        }
      >
        <Table
          dataSource={views}
          columns={viewColumns}
          scroll={{ x: 'max-content' }}
          rowKey="id"
          loading={viewsLoading}
          pagination={false}
          size="small"
          onRow={(record) => ({
            onClick: () => navigate(`/app/scheduling/calendar-views/${record.id}`),
            style: { cursor: 'pointer' },
          })}
        />
      </Drawer>

      {/* Create/Edit form drawer */}
      <Drawer
        title={editingView ? 'Edit Calendar View' : 'Create Calendar View'}
        open={formOpen}
        onClose={() => setFormOpen(false)}
        mask={false}
        width={formWidth}
        rootStyle={DRAWER_ROOT}
        destroyOnHidden
        extra={
          <Button type="primary" size="small" onClick={handleSave} loading={saving}>
            {editingView ? 'Update' : 'Create'}
          </Button>
        }
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="Name" rules={[{ required: true, message: 'Name is required' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="description" label="Description">
            <Input.TextArea rows={2} />
          </Form.Item>
          <Form.Item name="autoIncludeRoles" label="Roles" initialValue={[]}>
            <Select mode="multiple" options={ROLE_OPTIONS} placeholder="Select roles" />
          </Form.Item>
          <Form.Item name="includedLayerTypes" label="Layer Types" initialValue={[]}>
            <Select mode="multiple" options={LAYER_TYPE_OPTIONS} placeholder="Select layer types" />
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
