import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Button, Form, Input, Select, Space, Table, Typography, message } from "antd";
import {
  createContentPage,
  deleteContentPage,
  getAdminPages,
  updateContentPage,
  type ContentPage
} from "@modules/content/api/contentApi";

const emptyForm = { slug: "", title: "", body: "", status: "draft" };

export function AdminContentPanel(): JSX.Element {
  const queryClient = useQueryClient();
  const [messageApi, contextHolder] = message.useMessage();
  const [form, setForm] = useState(emptyForm);
  const [editingId, setEditingId] = useState<string | null>(null);

  const { data: pages, isLoading } = useQuery({
    queryKey: ["admin-content-pages"],
    queryFn: getAdminPages
  });

  const saveMutation = useMutation({
    mutationFn: async () => {
      if (editingId) {
        return updateContentPage(editingId, {
          title: form.title,
          body: form.body,
          status: form.status
        });
      }
      return createContentPage(form);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-content-pages"] });
      setForm(emptyForm);
      setEditingId(null);
      messageApi.success("Page saved");
    },
    onError: () => messageApi.error("Save failed")
  });

  const deleteMutation = useMutation({
    mutationFn: (pageId: string) => deleteContentPage(pageId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-content-pages"] });
      messageApi.success("Page deleted");
    }
  });

  function startEdit(page: ContentPage): void {
    setEditingId(page.id);
    setForm({
      slug: page.slug,
      title: page.title,
      body: page.body,
      status: page.status
    });
  }

  if (isLoading) {
    return <p className="wesp-admin-block">Loading content pages...</p>;
  }

  return (
    <div className="wesp-admin-grid">
      {contextHolder}
      <Typography.Title level={4} style={{ margin: 0 }}>
        Content pages
      </Typography.Title>
      <Form layout="vertical" onFinish={() => saveMutation.mutate()}>
        <Form.Item label="Slug">
          <Input
            placeholder="Slug"
            value={form.slug}
            disabled={Boolean(editingId)}
            onChange={(event) => setForm((prev) => ({ ...prev, slug: event.target.value }))}
          />
        </Form.Item>
        <Form.Item label="Title">
          <Input
            placeholder="Title"
            value={form.title}
            onChange={(event) => setForm((prev) => ({ ...prev, title: event.target.value }))}
          />
        </Form.Item>
        <Form.Item label="Body (HTML)">
          <Input.TextArea
            placeholder="Body (HTML)"
            value={form.body}
            rows={6}
            onChange={(event) => setForm((prev) => ({ ...prev, body: event.target.value }))}
          />
        </Form.Item>
        <Form.Item label="Status">
          <Select
            value={form.status}
            onChange={(value) => setForm((prev) => ({ ...prev, status: value }))}
            options={[{ value: "draft" }, { value: "published" }]}
          />
        </Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={saveMutation.isPending}>
            {editingId ? "Update page" : "Create page"}
          </Button>
          {editingId ? (
            <Button
              onClick={() => {
                setEditingId(null);
                setForm(emptyForm);
              }}
            >
              Cancel
            </Button>
          ) : null}
        </Space>
      </Form>

      <Table
        rowKey="id"
        dataSource={pages ?? []}
        pagination={false}
        columns={[
          {
            title: "Title",
            dataIndex: "title",
            render: (title: string, page: ContentPage) => (
              <Space direction="vertical" size={0}>
                <strong>{title}</strong>
                <Typography.Text type="secondary">{page.slug}</Typography.Text>
              </Space>
            )
          },
          { title: "Status", dataIndex: "status" },
          {
            title: "Actions",
            render: (_, page: ContentPage) => (
              <Space>
                <Button onClick={() => startEdit(page)}>Edit</Button>
                <Button danger onClick={() => deleteMutation.mutate(page.id)}>
                  Delete
                </Button>
              </Space>
            )
          }
        ]}
      />
    </div>
  );
}
