import { useState, useEffect, useCallback } from 'react';
import {
  List,
  Button,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Tooltip,
  Space,
  message,
  Typography,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  SyncOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { CalendarFeed, CalendarFeedInterval } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const INTERVAL_OPTIONS: { value: CalendarFeedInterval; label: string }[] = [
  { value: 'FIFTEEN_MIN', label: 'Every 15 minutes' },
  { value: 'HOURLY', label: 'Hourly' },
  { value: 'SIX_HOUR', label: 'Every 6 hours' },
  { value: 'DAILY', label: 'Daily' },
];

export default function CalendarFeedsPanel() {
  const [feeds, setFeeds] = useState<CalendarFeed[]>([]);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingFeed, setEditingFeed] = useState<CalendarFeed | null>(null);
  const [refreshingId, setRefreshingId] = useState<string | null>(null);
  const [form] = Form.useForm();

  const fetchFeeds = useCallback(async () => {
    try {
      const { data } = await api.get<{ feeds: CalendarFeed[] }>('/calendar/feeds');
      setFeeds(data.feeds);
    } catch {
      // ignore
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (editingFeed) {
        await api.patch(`/calendar/feeds/${editingFeed.id}`, values);
        message.success('Feed updated');
      } else {
        await api.post('/calendar/feeds', values);
        message.success('Feed added');
      }
      setModalOpen(false);
      setEditingFeed(null);
      form.resetFields();
      await fetchFeeds();
    } catch {
      message.error('Failed to save feed');
    }
  };

  const handleDelete = (feed: CalendarFeed) => {
    Modal.confirm({
      title: 'Delete feed?',
      content: `Remove "${feed.name}" and all its imported events?`,
      okText: 'Delete',
      okType: 'danger',
      onOk: async () => {
        try {
          await api.delete(`/calendar/feeds/${feed.id}`);
          message.success('Feed deleted');
          await fetchFeeds();
        } catch {
          message.error('Failed to delete feed');
        }
      },
    });
  };

  const handleRefresh = async (feed: CalendarFeed) => {
    setRefreshingId(feed.id);
    try {
      await api.post(`/calendar/feeds/${feed.id}/refresh`);
      message.success('Feed refreshed');
      await fetchFeeds();
    } catch {
      message.error('Failed to refresh feed');
    } finally {
      setRefreshingId(null);
    }
  };

  const openEdit = (feed: CalendarFeed) => {
    setEditingFeed(feed);
    form.setFieldsValue({
      name: feed.name,
      url: feed.url,
      refreshInterval: feed.refreshInterval,
    });
    setModalOpen(true);
  };

  const openAdd = () => {
    setEditingFeed(null);
    form.resetFields();
    setModalOpen(true);
  };

  const statusTag = (feed: CalendarFeed) => {
    const colorMap: Record<string, string> = { OK: 'green', ERROR: 'red', PENDING: 'gold' };
    const tag = (
      <Tag color={colorMap[feed.lastStatus] ?? 'default'}>
        {feed.lastStatus}
      </Tag>
    );
    if (feed.lastStatus === 'ERROR' && feed.lastError) {
      return <Tooltip title={feed.lastError}>{tag}</Tooltip>;
    }
    return tag;
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <Text strong>External Feeds</Text>
        <Button size="small" icon={<PlusOutlined />} onClick={openAdd}>
          Add Feed
        </Button>
      </div>

      <List
        size="small"
        loading={loading}
        dataSource={feeds}
        locale={{ emptyText: 'No external feeds' }}
        renderItem={(feed) => (
          <List.Item
            actions={[
              <Button
                key="edit"
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => openEdit(feed)}
              />,
              <Button
                key="refresh"
                type="text"
                size="small"
                icon={<SyncOutlined spin={refreshingId === feed.id} />}
                onClick={() => handleRefresh(feed)}
              />,
              <Button
                key="delete"
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDelete(feed)}
              />,
            ]}
          >
            <List.Item.Meta
              title={
                <Space size={8}>
                  <Text style={{ fontSize: 13 }}>{feed.name}</Text>
                  {statusTag(feed)}
                </Space>
              }
              description={
                <Space size={4} style={{ fontSize: 11 }}>
                  <span>{feed.itemCount} events</span>
                  {feed.lastFetchedAt && (
                    <span>· {dayjs(feed.lastFetchedAt).fromNow()}</span>
                  )}
                </Space>
              }
            />
          </List.Item>
        )}
      />

      <Modal
        title={editingFeed ? 'Edit Feed' : 'Add External Feed'}
        open={modalOpen}
        onOk={handleSubmit}
        onCancel={() => {
          setModalOpen(false);
          setEditingFeed(null);
          form.resetFields();
        }}
        okText={editingFeed ? 'Save' : 'Add'}
        destroyOnClose
      >
        <Form form={form} layout="vertical" initialValues={{ refreshInterval: 'HOURLY' }}>
          <Form.Item name="name" label="Name" rules={[{ required: true, message: 'Enter a name' }]}>
            <Input placeholder="e.g. Work Calendar" />
          </Form.Item>
          <Form.Item
            name="url"
            label="ICS URL"
            rules={[
              { required: true, message: 'Enter an ICS URL' },
              { type: 'url', message: 'Enter a valid URL' },
            ]}
          >
            <Input placeholder="https://example.com/calendar.ics" />
          </Form.Item>
          <Form.Item name="refreshInterval" label="Refresh Interval">
            <Select options={INTERVAL_OPTIONS} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
