"use client";

import { useParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { Alert, Button, Card, Form, Input, Space, Spin } from "antd";

import { BlockEditor, type SiteContentBlock } from "@/components/site/BlockEditor";
import { cmsSiteFetch } from "@/lib/site-cms-api";

type PageDetail = {
  id: string;
  title: string;
  slug: string;
  status: string;
  seoTitle: string | null;
  seoDescription: string | null;
  contentJson: { blocks?: SiteContentBlock[] };
};

export default function SitePageEditPage() {
  const params = useParams();
  const id = typeof params.id === "string" ? params.id : "";
  const [form] = Form.useForm();
  const [blocks, setBlocks] = useState<SiteContentBlock[]>([]);
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    const res = await cmsSiteFetch<PageDetail>(`/cms/site/pages/${id}`);
    if (!res.ok) {
      setErr(res.message);
      setLoading(false);
      return;
    }
    form.setFieldsValue({
      title: res.data.title,
      slug: res.data.slug,
      seoTitle: res.data.seoTitle ?? "",
      seoDescription: res.data.seoDescription ?? "",
    });
    setBlocks(Array.isArray(res.data.contentJson?.blocks) ? res.data.contentJson.blocks : []);
    setLoading(false);
  }, [form, id]);

  useEffect(() => {
    void load();
  }, [load]);

  const save = async () => {
    const values = await form.validateFields();
    const res = await cmsSiteFetch(`/cms/site/pages/${id}`, {
      method: "PATCH",
      body: JSON.stringify({ ...values, contentJson: { blocks } }),
    });
    if (!res.ok) setErr(res.message);
    else setErr(null);
  };

  const publish = async () => {
    const res = await cmsSiteFetch(`/cms/site/pages/${id}/publish`, { method: "POST" });
    if (!res.ok) setErr(res.message);
    else void load();
  };

  if (loading) {
    return (
      <div className="py-16 text-center">
        <Spin />
      </div>
    );
  }

  return (
    <Card className="cms-surface-card" styles={{ body: { padding: "24px 28px" } }}>
      <h1 className="mb-4 text-lg font-semibold text-white/90">Sửa trang</h1>
      {err ? <Alert type="warning" message={err} showIcon className="mb-4" /> : null}
      <Form form={form} layout="vertical" className="max-w-2xl">
        <Form.Item name="title" label="Tiêu đề" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="slug" label="Slug" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="seoTitle" label="SEO title">
          <Input />
        </Form.Item>
        <Form.Item name="seoDescription" label="SEO description">
          <Input.TextArea rows={2} />
        </Form.Item>
      </Form>
      <div className="mt-6 max-w-3xl">
        <BlockEditor blocks={blocks} onChange={setBlocks} />
      </div>
      <Space className="mt-6" wrap>
        <Button type="primary" onClick={() => void save()}>
          Lưu
        </Button>
        <Button onClick={() => void publish()}>Xuất bản</Button>
      </Space>
    </Card>
  );
}
