import { useState } from 'react';
import { Alert, Checkbox, Form, Input, Modal, Space, Tag, Typography, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import type { ColDef } from '@ag-grid-community/core';
import PageContainer from '@/components/common/PageContainer';
import SearchForm from '@/components/common/SearchForm';
import DataGrid from '@/components/common/DataGrid';
import PermissionButton from '@/components/common/PermissionButton';
import CodeBadge from '@/components/common/CodeBadge';
import { noticeApi, NoticeRow, NoticeSaveReq, NoticeSearchParam } from '@/api/notice';
import { GRAY, RADIUS, SHADOW, COLOR_ERROR } from '@/theme/tokens';

const { Text } = Typography;
const { TextArea } = Input;

const COLUMNS: ColDef<NoticeRow>[] = [
  {
    field: 'isPinned', headerName: '고정', width: 70,
    cellRenderer: (p: { value: boolean }) =>
      p.value ? <Tag color="error" style={{ margin: 0, fontSize: 11 }}>고정</Tag> : null,
  },
  {
    field: 'noticeType', headerName: '유형', width: 100,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="NOTICE_TYPE" value={p.value} />,
  },
  { field: 'title',      headerName: '제목',   flex: 1 },
  { field: 'authorName', headerName: '작성자', width: 110 },
  { field: 'viewCount',  headerName: '조회수', width: 80, type: 'numericColumn' },
  { field: 'publishedAt', headerName: '게시일', width: 120 },
  { field: 'expiresAt',  headerName: '만료일', width: 120 },
  {
    field: 'status', headerName: '상태', width: 90,
    cellRenderer: (p: { value: string }) => <CodeBadge groupCode="NOTICE_STATUS" value={p.value} />,
  },
];

export default function Notices() {
  const qc = useQueryClient();
  const [params, setParams] = useState<NoticeSearchParam>({ pageSize: 50 });
  const [modalOpen, setModalOpen] = useState(false);
  const [editingNotice, setEditingNotice] = useState<NoticeRow | null>(null);
  const [form] = Form.useForm();

  const { data, isLoading, isError } = useQuery({
    queryKey: ['notices', params],
    queryFn: () => noticeApi.list(params),
    retry: false,
  });

  const rows = data?.list ?? [];

  const openCreate = () => { setEditingNotice(null); form.resetFields(); setModalOpen(true); };
  const openEdit = (row: NoticeRow) => { setEditingNotice(row); form.setFieldsValue(row); setModalOpen(true); };

  const handleSave = async () => {
    const values = await form.validateFields() as NoticeSaveReq;
    try {
      if (editingNotice) {
        await noticeApi.update(editingNotice.noticeId, values);
        message.success('공지 수정 완료');
      } else {
        await noticeApi.create(values);
        message.success('공지 등록 완료');
      }
      qc.invalidateQueries({ queryKey: ['notices'] });
      setModalOpen(false);
    } catch { /* handled */ }
  };

  const handleDelete = (id: number) => Modal.confirm({
    title: '공지 삭제', content: '삭제하시겠습니까?',
    onOk: async () => {
      await noticeApi.delete(id);
      message.success('삭제 완료');
      qc.invalidateQueries({ queryKey: ['notices'] });
    },
  });

  return (
    <PageContainer
      title="공지사항 관리"
      description="시스템 공지사항 등록 및 관리"
      extra={
        <PermissionButton menuCode="NOTICES" permCode="CREATE" type="primary" onClick={openCreate}>
          + 공지 등록
        </PermissionButton>
      }
    >
      {isError && (
        <Alert type="warning" showIcon message="API 미응답" description="/api/notices 를 확인하세요." style={{ marginBottom: 16 }} />
      )}

      <SearchForm
        conditions={[
          { type: 'text', name: 'title',      label: '제목',   span: 8 },
          { type: 'code', name: 'noticeType', label: '유형',   groupCode: 'NOTICE_TYPE', span: 6 },
        ]}
        onSearch={(v) => setParams({ ...v as NoticeSearchParam, pageSize: 50 })}
        onReset={() => setParams({ pageSize: 50 })}
      />

      <ProCard style={{ background: '#fff', borderRadius: RADIUS.lg, border: `1px solid ${GRAY[100]}`, boxShadow: SHADOW.sm }}>
        <DataGrid<NoticeRow>
          rows={rows}
          columns={[
            ...COLUMNS,
            {
              headerName: '액션', width: 160, pinned: 'right',
              cellRenderer: (p: { data: NoticeRow }) => (
                <Space>
                  <PermissionButton menuCode="NOTICES" permCode="UPDATE" size="small" onClick={() => openEdit(p.data)}>수정</PermissionButton>
                  <PermissionButton menuCode="NOTICES" permCode="DELETE" size="small" danger onClick={() => handleDelete(p.data.noticeId)}>삭제</PermissionButton>
                </Space>
              ),
            },
          ]}
          loading={isLoading}
          height={600}
          rowKey="noticeId"
        />
      </ProCard>

      <Modal
        title={editingNotice ? '공지 수정' : '공지 등록'}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        okText="저장"
        cancelText="취소"
        width={640}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="제목" rules={[{ required: true }]}><Input /></Form.Item>
          <Form.Item name="noticeType" label="유형" rules={[{ required: true }]}>
            <Input placeholder="GENERAL / IMPORTANT / SYSTEM" />
          </Form.Item>
          <Form.Item name="content" label="내용" rules={[{ required: true }]}>
            <TextArea rows={6} />
          </Form.Item>
          <Form.Item name="isPinned" label="고정 여부" valuePropName="checked">
            <Checkbox>상단 고정</Checkbox>
          </Form.Item>
          <Form.Item name="publishedAt" label="게시일">
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item name="expiresAt" label="만료일">
            <Input placeholder="YYYY-MM-DD" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
}
