import { useState, useEffect } from 'react';
import { useNavigate, useOutletContext } from 'react-router-dom';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Tag,
  Space,
  Popconfirm,
  message,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import { useMobile } from '@/hooks/useMobile';
import type { AdminCalendarView } from '@/types/api';
import type { AppOutletContext } from '@/components/AppLayout';
import { ROLE_COLORS, ROLE_OPTIONS } from '@/utils/role-constants';

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 AdminCalendarPage() {
  const navigate = useNavigate();
  const { isMobile } = useMobile();
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [views, setViews] = useState<AdminCalendarView[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingView, setEditingView] = useState<AdminCalendarView | null>(null);
  const [saving, setSaving] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    setPageHeader({ title: 'Calendar Views', subtitle: 'Manage role-based shared calendar views' });
  }, [setPageHeader]);

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

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

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

  const openEdit = (view: AdminCalendarView) => {
    setEditingView(view);
    form.setFieldsValue({
      name: view.name,
      description: view.description,
      autoIncludeRoles: view.autoIncludeRoles,
      includedLayerTypes: view.includedLayerTypes,
    });
    setModalOpen(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');
      }
      setModalOpen(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 columns = [
    {
      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: 'Layer Types',
      dataIndex: 'includedLayerTypes',
      key: 'layerTypes',
      responsive: ['md'] as any,
      render: (types: string[]) => (
        <Space size={4} wrap>
          {types.map((t) => (
            <Tag key={t}>{t}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: 'Users',
      dataIndex: 'userCount',
      key: 'userCount',
      width: 80,
      responsive: ['lg'] as any,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      responsive: ['md'] as any,
      render: (d: string) => dayjs(d).format('MMM D, YYYY'),
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 100,
      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={(e) => { e?.stopPropagation(); handleDelete(record.id); }}
            onCancel={(e) => e?.stopPropagation()}
          >
            <Button
              type="text"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={(e) => e.stopPropagation()}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
          Create View
        </Button>
      </div>

      <Table
        dataSource={views}
        columns={columns}
        scroll={{ x: 'max-content' }}
        rowKey="id"
        loading={loading}
        pagination={false}
        onRow={(record) => ({
          onClick: () => navigate(`/app/scheduling/calendar-views/${record.id}`),
          style: { cursor: 'pointer' },
        })}
      />

      <Modal
        title={editingView ? 'Edit Calendar View' : 'Create Calendar View'}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        confirmLoading={saving}
        width={isMobile ? '100%' : undefined}
        destroyOnHidden
      >
        <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>
      </Modal>
    </div>
  );
}
