import React, { useState, useCallback, useEffect } from 'react';
import { Modal, Form, Input, TreeSelect, message } from 'antd';
import type { SavedCanvas } from './types';
import { publishCanvas } from './canvasApi';
import { useTranslation } from 'react-i18next';
import { customRequest } from 'helpers/http';

interface RawPage {
  id: number;
  code: string;
  name: string;
  zhName?: string;
  enName?: string;
  parentId?: number | null;
  sortOrder?: number;
}

interface TreeNode {
  title: React.ReactNode;
  value: string;
  key: string;
  children?: TreeNode[];
}

function buildTree(pages: RawPage[], rootTitle: string): TreeNode[] {
  const children = new Map<number | null, RawPage[]>();
  for (const p of pages) {
    const pid = p.parentId ?? null;
    if (!children.has(pid)) children.set(pid, []);
    children.get(pid)!.push(p);
  }
  function makeNode(p: RawPage): TreeNode {
    const label = p.zhName || p.enName || p.name;
    return {
      title: label,
      value: p.code,
      key: p.code,
      children: (children.get(p.id) ?? [])
        .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
        .map(makeNode),
    };
  }
  return [
    { title: rootTitle, value: '__root__', key: '__root__' },
    ...(children.get(null) ?? [])
      .sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
      .map(makeNode),
  ];
}

function toSlug(name: string): string {
  return (
    name
      .toLowerCase()
      .replace(/[\s_]+/g, '-')
      .replace(/[^a-z0-9一-鿿-]/g, '')
      .replace(/^-+|-+$/g, '') || 'canvas-page'
  );
}

interface PublishModalProps {
  open: boolean;
  onClose: () => void;
  activeCanvas: SavedCanvas;
  onPublishSuccess?: () => void;
}

const PublishModal: React.FC<PublishModalProps> = ({
  open,
  onClose,
  activeCanvas,
  onPublishSuccess,
}) => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [pagesLoading, setPagesLoading] = useState(false);
  const { t } = useTranslation();

  // Load page tree when modal opens
  useEffect(() => {
    if (!open) return;
    setPagesLoading(true);
    customRequest<{ data: RawPage[] }>('page/findMany', 'POST', {
      where: {},
      orderBy: { sortOrder: 'asc' },
    })
      .then((data) => {
        const pages: RawPage[] = data?.data ?? [];
        setTreeData(buildTree(pages, t('canvas.publishModal.rootPage')));
      })
      .catch(() => message.error(t('canvas.publishModal.loadPagesFailed')))
      .finally(() => setPagesLoading(false));
  }, [open, t]);

  // Auto-generate slug from pageName
  const handleNameChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      const name = e.target.value;
      form.setFieldValue('slug', toSlug(name));
    },
    [form],
  );

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

      const parentPageCode =
        values.parentPageCode === '__root__'
          ? undefined
          : values.parentPageCode;

      await publishCanvas(activeCanvas.id, {
        slug: values.slug,
        pageName: values.pageName,
        parentPageCode,
      });

      message.success(t('canvas.publishModal.success'));
      form.resetFields();
      onPublishSuccess?.();
      onClose();
    } catch {
      // form validation or API error
    } finally {
      setSubmitting(false);
    }
  }, [activeCanvas.id, form, onClose, onPublishSuccess, t]);

  const handleCancel = useCallback(() => {
    form.resetFields();
    onClose();
  }, [form, onClose]);

  return (
    <Modal
      title={t('canvas.publishModal.title')}
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      okText={t('canvas.publishModal.publishBtn')}
      cancelText={t('canvas.publishModal.cancel')}
      confirmLoading={submitting}
      width={480}
    >
      <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
        <Form.Item
          name="pageName"
          label={t('canvas.publishModal.pageName')}
          rules={[
            {
              required: true,
              message: t('canvas.publishModal.pageNameRequired'),
            },
          ]}
        >
          <Input
            placeholder={t('canvas.publishModal.pageNamePlaceholder')}
            autoFocus
            onChange={handleNameChange}
          />
        </Form.Item>
        <Form.Item
          name="slug"
          label="Slug"
          rules={[{ required: true, message: 'Please enter a slug' }]}
          initialValue={toSlug(activeCanvas.name)}
        >
          <Input placeholder="game-dashboard" />
        </Form.Item>
        <Form.Item
          name="parentPageCode"
          label={t('canvas.publishModal.parentPage')}
          rules={[
            {
              required: true,
              message: t('canvas.publishModal.parentPageRequired'),
            },
          ]}
        >
          <TreeSelect
            placeholder={t('canvas.publishModal.parentPagePlaceholder')}
            loading={pagesLoading}
            treeData={treeData}
            treeDefaultExpandAll
            showSearch
            treeNodeFilterProp="title"
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default PublishModal;
