import { useState, useEffect, useCallback } from 'react';
import {
  Typography,
  Button,
  Card,
  Row,
  Col,
  Drawer,
  Form,
  Input,
  Select,
  Checkbox,
  Space,
  Tag,
  Empty,
  Skeleton,
  Grid,
  message,
  Segmented,
} from 'antd';
import {
  PlusOutlined,
  CalendarOutlined,
  TeamOutlined,
  GlobalOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import FeatureGate from '@/components/FeatureGate';
import type { SharedCalendarView, SharedViewScope } from '@/types/api';

const { Text, Paragraph } = Typography;

const LAYER_TYPE_OPTIONS = [
  { label: 'Personal Events', value: 'USER' },
  { label: 'Shifts', value: 'SYSTEM_SHIFTS' },
  { label: 'Ticketed Events', value: 'SYSTEM_EVENTS' },
  { label: 'Scheduling Polls', value: 'SYSTEM_POLLS' },
];

export default function SharedCalendarsPage() {
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [views, setViews] = useState<SharedCalendarView[]>([]);
  const [loading, setLoading] = useState(true);
  const [createModalOpen, setCreateModalOpen] = useState(false);
  const [creating, setCreating] = useState(false);
  const [form] = Form.useForm();

  const fetchViews = useCallback(async () => {
    try {
      const { data } = await api.get<{ views: SharedCalendarView[] }>('/calendar/shared');
      setViews(data.views);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = async (values: any) => {
    setCreating(true);
    try {
      await api.post('/calendar/shared', {
        name: values.name,
        description: values.description || null,
        includedLayerTypes: values.includedLayerTypes || ['USER'],
        shareScope: values.shareScope || 'MEMBERS',
      });
      message.success('Shared calendar created');
      setCreateModalOpen(false);
      form.resetFields();
      await fetchViews();
    } catch {
      message.error('Failed to create shared calendar');
    } finally {
      setCreating(false);
    }
  };

  const handleRespond = async (viewId: string, status: 'ACCEPTED' | 'DECLINED') => {
    try {
      await api.patch(`/calendar/shared/${viewId}/respond`, { status });
      message.success(status === 'ACCEPTED' ? 'Invitation accepted' : 'Invitation declined');
      await fetchViews();
    } catch {
      message.error('Failed to respond to invitation');
    }
  };

  const scopeIcon = (scope: SharedViewScope) =>
    scope === 'PUBLIC' ? <GlobalOutlined /> : <TeamOutlined />;

  return (
    <FeatureGate feature="enableSocialCalendar">
      <div style={{ padding: '12px 0' }}>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            marginBottom: 16,
          }}
        >
          <Space>
            <CalendarOutlined style={{ fontSize: 20 }} />
            <Segmented
              options={['My Calendar', 'Shared']}
              value="Shared"
              onChange={(val) => {
                if (val === 'My Calendar') navigate('/volunteer/calendar');
              }}
            />
          </Space>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalOpen(true)}
          >
            {!isMobile && 'Create'}
          </Button>
        </div>

        {loading ? (
          <Skeleton active paragraph={{ rows: 6 }} />
        ) : views.length === 0 ? (
          <Empty description="No shared calendars yet. Create one or wait for an invite." />
        ) : (
          <Row gutter={[12, 12]}>
            {views.map((view) => (
              <Col key={view.id} xs={24} sm={12} lg={8}>
                <Card
                  hoverable
                  onClick={() => {
                    if (view.myStatus === 'ACCEPTED' || view.ownerId === view.owner?.id) {
                      navigate(`/volunteer/calendar/shared/${view.id}`);
                    }
                  }}
                  style={{ height: '100%' }}
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <Text strong style={{ fontSize: 15 }}>{view.name}</Text>
                      <Tag icon={scopeIcon(view.shareScope)} style={{ margin: 0 }}>
                        {view.shareScope}
                      </Tag>
                    </div>

                    {view.description && (
                      <Paragraph type="secondary" ellipsis={{ rows: 2 }} style={{ margin: 0, fontSize: 13 }}>
                        {view.description}
                      </Paragraph>
                    )}

                    <Space size={4}>
                      <TeamOutlined />
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        {view._count?.members || 0} member{(view._count?.members || 0) !== 1 ? 's' : ''}
                      </Text>
                      {view.owner && (
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          by {view.owner.name || view.owner.email}
                        </Text>
                      )}
                    </Space>

                    {view.myStatus === 'INVITED' && (
                      <Space style={{ marginTop: 4 }}>
                        <Button
                          size="small"
                          type="primary"
                          icon={<CheckOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRespond(view.id, 'ACCEPTED');
                          }}
                        >
                          Accept
                        </Button>
                        <Button
                          size="small"
                          danger
                          icon={<CloseOutlined />}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRespond(view.id, 'DECLINED');
                          }}
                        >
                          Decline
                        </Button>
                      </Space>
                    )}

                    {view.myStatus === 'DECLINED' && (
                      <Tag color="red" style={{ marginTop: 4 }}>Declined</Tag>
                    )}
                  </Space>
                </Card>
              </Col>
            ))}
          </Row>
        )}

        <Drawer
          title="Create Shared Calendar"
          open={createModalOpen}
          onClose={() => setCreateModalOpen(false)}
          placement="right"
          width={480}
          mask={false}
          rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
          extra={
            <Button type="primary" loading={creating} onClick={() => form.submit()}>
              Create
            </Button>
          }
        >
          <Form form={form} layout="vertical" onFinish={handleCreate}>
            <Form.Item
              name="name"
              label="Name"
              rules={[{ required: true, message: 'Please enter a name' }]}
            >
              <Input placeholder="e.g. Team Calendar" />
            </Form.Item>
            <Form.Item name="description" label="Description">
              <Input.TextArea rows={2} placeholder="Optional description" />
            </Form.Item>
            <Form.Item
              name="includedLayerTypes"
              label="Include Layer Types"
              initialValue={['USER']}
            >
              <Checkbox.Group options={LAYER_TYPE_OPTIONS} />
            </Form.Item>
            <Form.Item
              name="shareScope"
              label="Visibility"
              initialValue="MEMBERS"
            >
              <Select
                options={[
                  { value: 'MEMBERS', label: 'Members Only' },
                  { value: 'PUBLIC', label: 'Public (anyone with link)' },
                ]}
              />
            </Form.Item>
          </Form>
        </Drawer>
      </div>
    </FeatureGate>
  );
}
