import { useState, useEffect, useCallback } from 'react';
import {
  List,
  Button,
  Modal,
  Form,
  Checkbox,
  Select,
  Typography,
  message,
} from 'antd';
import {
  PlusOutlined,
  CopyOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { CalendarExportToken, CalendarLayer } from '@/types/api';

const { Text } = Typography;

interface Props {
  layers: CalendarLayer[];
}

export default function CalendarExportPanel({ layers }: Props) {
  const [tokens, setTokens] = useState<CalendarExportToken[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();

  const fetchTokens = useCallback(async () => {
    try {
      const { data } = await api.get<{ tokens: CalendarExportToken[] }>('/calendar/export/tokens');
      setTokens(data.tokens);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      await api.post('/calendar/export/tokens', {
        includePersonal: values.includePersonal ?? true,
        includeLayers: values.includeLayers?.length ? values.includeLayers : null,
      });
      message.success('Export link created');
      setModalOpen(false);
      form.resetFields();
      await fetchTokens();
    } catch {
      message.error('Failed to create export link');
    }
  };

  const handleRevoke = (token: CalendarExportToken) => {
    Modal.confirm({
      title: 'Revoke export link?',
      content: 'Anyone using this link will no longer be able to access your calendar.',
      okText: 'Revoke',
      okType: 'danger',
      onOk: async () => {
        try {
          await api.delete(`/calendar/export/tokens/${token.id}`);
          message.success('Export link revoked');
          await fetchTokens();
        } catch {
          message.error('Failed to revoke link');
        }
      },
    });
  };

  const copyUrl = (token: string) => {
    const url = `${window.location.origin}/api/calendar/feed/${token}.ics`;
    navigator.clipboard.writeText(url).then(
      () => message.success('URL copied'),
      () => message.error('Failed to copy'),
    );
  };

  const describeScope = (t: CalendarExportToken) => {
    const parts: string[] = [];
    if (t.includePersonal) parts.push('Personal events');
    if (t.includeLayers?.length) {
      const names = t.includeLayers
        .map((id) => layers.find((l) => l.id === id)?.name)
        .filter(Boolean);
      if (names.length) parts.push(names.join(', '));
    }
    return parts.length ? parts.join(' + ') : 'All layers';
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <Text strong>Export Calendar</Text>
        <Button size="small" icon={<PlusOutlined />} onClick={() => { form.resetFields(); setModalOpen(true); }}>
          Create Export Link
        </Button>
      </div>

      <List
        size="small"
        loading={loading}
        dataSource={tokens}
        locale={{ emptyText: 'No export links' }}
        renderItem={(t) => (
          <List.Item
            actions={[
              <Button
                key="copy"
                type="text"
                size="small"
                icon={<CopyOutlined />}
                onClick={() => copyUrl(t.token)}
              />,
              <Button
                key="revoke"
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleRevoke(t)}
              />,
            ]}
          >
            <List.Item.Meta
              title={<Text style={{ fontSize: 13 }}>{describeScope(t)}</Text>}
              description={
                <Text style={{ fontSize: 11 }} type="secondary">
                  Created {dayjs(t.createdAt).format('MMM D, YYYY')}
                </Text>
              }
            />
          </List.Item>
        )}
      />

      <Modal
        title="Create Export Link"
        open={modalOpen}
        onOk={handleCreate}
        onCancel={() => { setModalOpen(false); form.resetFields(); }}
        okText="Create"
        destroyOnClose
      >
        <Form form={form} layout="vertical" initialValues={{ includePersonal: true }}>
          <Form.Item name="includePersonal" valuePropName="checked">
            <Checkbox>Include personal events</Checkbox>
          </Form.Item>
          <Form.Item name="includeLayers" label="Include specific layers (optional)">
            <Select
              mode="multiple"
              allowClear
              placeholder="All layers"
              options={layers.map((l) => ({ value: l.id, label: l.name }))}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
