import { useState } from 'react';
import { Drawer, Form, Input, DatePicker, Select, Switch, Button, message, theme } from 'antd';
import { FileMarkdownOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { AuthorEntry } from '@/hooks/useBlogAuthors';

interface NewBlogPostModalProps {
  open: boolean;
  onClose: () => void;
  onCreated: (path: string) => void;
  authors: Record<string, AuthorEntry>;
  categories: string[];
}

function slugify(text: string): string {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_]+/g, '-')
    .replace(/-+/g, '-')
    .replace(/^-|-$/g, '');
}

export function NewBlogPostModal({
  open,
  onClose,
  onCreated,
  authors,
  categories,
}: NewBlogPostModalProps) {
  const { token } = theme.useToken();
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();

  const titleValue = Form.useWatch('title', form) as string | undefined;
  const dateValue = Form.useWatch('date', form) as dayjs.Dayjs | undefined;

  const slug = titleValue ? slugify(titleValue) : '';
  const dateStr = dateValue ? dateValue.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD');
  const previewFilename = slug ? `blog/posts/${dateStr}-${slug}.md` : '';

  const authorOptions = Object.entries(authors || {}).map(([key, entry]) => ({
    label: entry.name,
    value: key,
  }));

  const categoryOptions = (categories || []).map((cat) => ({
    label: cat,
    value: cat,
  }));

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setSubmitting(true);

      const res = await api.post<{ path: string }>('/docs/blog/posts', {
        title: values.title,
        date: values.date ? values.date.format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD'),
        authors: values.authors ?? [],
        categories: values.categories ?? [],
        draft: values.draft ?? true,
      });

      messageApi.success('Blog post created');
      form.resetFields();
      onCreated(res.data.path);
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { error?: { message?: string } } } })?.response?.data
          ?.error?.message || 'Failed to create blog post';
      messageApi.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  const handleClose = () => {
    form.resetFields();
    onClose();
  };

  return (
    <Drawer
      title={
        <span>
          <FileMarkdownOutlined style={{ marginRight: 8 }} />
          New Blog Post
        </span>
      }
      open={open}
      onClose={handleClose}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
      extra={
        <Button type="primary" onClick={handleSubmit} loading={submitting}>
          Create
        </Button>
      }
    >
      {contextHolder}
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          date: dayjs(),
          draft: true,
        }}
        style={{ marginTop: 16 }}
      >
        <Form.Item
          name="title"
          label="Title"
          rules={[{ required: true, message: 'Title is required' }]}
        >
          <Input placeholder="My New Blog Post" autoFocus />
        </Form.Item>

        {previewFilename && (
          <div
            style={{
              marginTop: -12,
              marginBottom: 16,
              padding: '6px 10px',
              borderRadius: token.borderRadius,
              background: token.colorFillQuaternary,
              fontSize: 12,
              color: token.colorTextSecondary,
              fontFamily: 'monospace',
            }}
          >
            {previewFilename}
          </div>
        )}

        <Form.Item name="date" label="Date">
          <DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item name="authors" label="Author(s)">
          <Select
            mode="multiple"
            placeholder="Select authors"
            options={authorOptions}
            allowClear
          />
        </Form.Item>

        <Form.Item name="categories" label="Categories">
          <Select
            mode="tags"
            placeholder="Add categories"
            options={categoryOptions}
            allowClear
          />
        </Form.Item>

        <Form.Item name="draft" label="Draft" valuePropName="checked">
          <Switch />
        </Form.Item>
      </Form>
    </Drawer>
  );
}
