import { useMemo, useState } from 'react'
import Modal from '../../components/DraggableModal'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Button,
  Card,
  Form,
  Input,
  Select,
  Space,
  Typography,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import { EditOutlined, QuestionCircleOutlined, SearchOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'

type InquiryRow = {
  id: number
  no?: number
  title?: string
  answer?: string
  status?: string
  authorName?: string
  createdDate?: string
  content?: string
  reply?: string
}

type InquiryData = {
  total: number
  list: InquiryRow[]
}

export default function CsInquiryPage() {
  const qc = useQueryClient()
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [open, setOpen] = useState(false)
  const [detail, setDetail] = useState<InquiryRow | null>(null)
  const [filters, setFilters] = useState<Record<string, unknown>>({
    searchType: '제목',
    page: 0,
    size: 15,
    sort: 'createdAt,desc' })

  const query = useQuery({
    queryKey: ['cs-inquiries', filters],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<InquiryData>>(`${apiPrefix()}/cs/search`, { params: filters })
      return unwrap(data)
    } })

  const refresh = () => qc.invalidateQueries({ queryKey: ['cs-inquiries'] })

  const createMut = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const { data } = await client.post(`${apiPrefix()}/cs`, values)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('사용문의를 등록했습니다.')
      setOpen(false)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const openDetail = useMutation({
    mutationFn: async (id: number) => {
      const { data } = await client.get<ApiResponse<InquiryRow>>(`${apiPrefix()}/cs/${id}`)
      return unwrap(data)
    },
    onSuccess: (row) => setDetail(row),
    onError: (e: Error) => message.error(e.message) })

  const onSearch = (values: Record<string, unknown>) => {
    setFilters((prev) => ({
      ...prev,
      searchType: values.searchType || '제목',
      keyword: values.keyword,
      page: 0,
      size: Number(values.size ?? prev.size ?? 15) }))
  }

  const onReset = () => {
    form.setFieldsValue({ searchType: '제목', keyword: undefined, size: 15 })
    setFilters({ searchType: '제목', page: 0, size: 15, sort: 'createdAt,desc' })
  }

  const columns = useMemo(() => [
    {
      title: '번호',
      dataIndex: 'no',
      width: 90,
      align: 'center' as const,
      sorter: true },
    {
      title: '제목',
      dataIndex: 'title',
      ellipsis: true,
      render: (v: string, row: InquiryRow) => (
        <Button type="link" className="cs-notice-title" onClick={() => openDetail.mutate(row.id)}>
          {v}
        </Button>
      ) },
    {
      title: '답변',
      dataIndex: 'answer',
      width: 120,
      align: 'center' as const,
      sorter: true },
    {
      title: '작성자',
      dataIndex: 'authorName',
      width: 100,
      align: 'center' as const,
      sorter: true },
    {
      title: '등록일',
      dataIndex: 'createdDate',
      width: 120,
      align: 'center' as const,
      sorter: true },
  ], [])

  return (
    <div className="stock-page cs-notice-page">
      <div className="stock-title">
        <div>
          <h2><QuestionCircleOutlined style={{ marginRight: 8 }} />사용문의</h2>
          <p>궁금하신 사항이나 사용상 문제가 있으시면 언제든지 내용을 남겨주세요. 담당자 확인 후 답변드리겠습니다.</p>
        </div>
        <Button type="primary" icon={<EditOutlined />} onClick={() => { editForm.resetFields(); setOpen(true) }}>
          사용문의 등록
        </Button>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form
          form={form}
          layout="inline"
          className="farebox-filter"
          initialValues={{ searchType: '제목', size: 15 }}
          onFinish={onSearch}
        >
          <div className="farebox-filter-row">
            <Form.Item name="searchType">
              <Select className="w-110" options={['제목', '작성자', '내용', '답변'].map((v) => ({ value: v, label: v }))} />
            </Form.Item>
            <Form.Item name="keyword">
              <Input className="w-230" allowClear />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>검색</Button>
                <Button onClick={onReset}>초기화</Button>
              </Space>
            </Form.Item>
            <Form.Item name="size" className="farebox-size">
              <Select
                className="w-150"
                options={[15, 30, 50, 100].map((n) => ({ value: n, label: `목록 ${n}개씩 보기` }))}
                onChange={(size) => setFilters((prev) => ({ ...prev, size, page: 0 }))}
              />
            </Form.Item>
          </div>
        </Form>
      </Card>

      <Card className="stock-table-card" size="small">
        <div className="farebox-table-toolbar">
          <Typography.Text>목록 {query.data?.total ?? 0}</Typography.Text>
        </div>
        <CareTable
          size="small"
          loading={query.isLoading}
          rowKey="id"
          dataSource={query.data?.list}
          columns={columns}
          pagination={{
            current: Number(filters.page ?? 0) + 1,
            pageSize: Number(filters.size ?? 15),
            total: query.data?.total ?? 0,
            showSizeChanger: false,
            onChange: (page) => setFilters((prev) => ({ ...prev, page: page - 1 })) }}
          onChange={(_p, _f, sorter) => {
            const s = Array.isArray(sorter) ? sorter[0] : sorter
            if (!s?.field) return
            const fieldMap: Record<string, string> = {
              no: 'id',
              answer: 'answer',
              authorName: 'authorName',
              createdDate: 'createdAt',
              title: 'title' }
            const field = fieldMap[String(s.field)] || String(s.field)
            setFilters((prev) => ({
              ...prev,
              sort: `${field},${s.order === 'ascend' ? 'asc' : 'desc'}`,
              page: 0 }))
          }}
          locale={{ emptyText: '등록된 사용문의가 없습니다.' }}
        />
      </Card>

      <Modal
        title="사용문의 등록"
        open={open}
        onCancel={() => setOpen(false)}
        footer={null}
        destroyOnClose
        width={640}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={(values) => createMut.mutate(values)}
        >
          <Form.Item name="title" label="제목" rules={[{ required: true, message: '제목을 입력하세요.' }]}>
            <Input maxLength={200} />
          </Form.Item>
          <Form.Item name="content" label="내용" rules={[{ required: true, message: '내용을 입력하세요.' }]}>
            <Input.TextArea rows={8} />
          </Form.Item>
          <div className="bbs-write-actions">
            <Button type="primary" htmlType="submit" loading={createMut.isPending}>등록</Button>
            <Button onClick={() => setOpen(false)}>취소</Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title={detail?.title || '사용문의'}
        open={!!detail}
        onCancel={() => setDetail(null)}
        footer={<Button onClick={() => setDetail(null)}>닫기</Button>}
        width={720}
        destroyOnClose
      >
        <div className="cs-notice-meta">
          <span>작성자 {detail?.authorName || '-'}</span>
          <span>등록일 {detail?.createdDate || '-'}</span>
          <span>{detail?.answer || detail?.status || '-'}</span>
        </div>
        <div className="cs-inquiry-section">
          <Typography.Text strong>문의내용</Typography.Text>
          <div className="cs-notice-body" style={{ whiteSpace: 'pre-wrap' }}>{detail?.content || '-'}</div>
        </div>
        <div className="cs-inquiry-section">
          <Typography.Text strong>답변</Typography.Text>
          <div className="cs-notice-body" style={{ whiteSpace: 'pre-wrap' }}>{detail?.reply || '답변 대기 중입니다.'}</div>
        </div>
      </Modal>
    </div>
  )
}
