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, FileTextOutlined, PlusOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'

type DeliveryRow = {
  id: number
  status?: string
  active?: boolean
  name?: string
  phone?: string
  memo?: string
  createdAt?: string
}

type DeliveryData = {
  total: number
  list: DeliveryRow[]
}

export default function DeliveryPage() {
  const qc = useQueryClient()
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<DeliveryRow | null>(null)
  const [selected, setSelected] = useState<number[]>([])
  const [filters, setFilters] = useState<Record<string, unknown>>({
    searchType: '업체명',
    page: 0,
    size: 15,
    sort: 'name,asc' })

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

  const refresh = () => {
    setSelected([])
    qc.invalidateQueries({ queryKey: ['deliveries'] })
  }

  const saveMut = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      if (editing?.id) {
        const { data } = await client.put(`${apiPrefix()}/deliveries/${editing.id}`, values)
        return unwrap(data)
      }
      const { data } = await client.post(`${apiPrefix()}/deliveries`, values)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success(editing ? '배송처를 수정했습니다.' : '배송처를 등록했습니다.')
      setOpen(false)
      setEditing(null)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const statusMut = useMutation({
    mutationFn: async (status: '사용' | '미사용') => {
      const { data } = await client.post(`${apiPrefix()}/deliveries/status`, { ids: selected, status })
      return unwrap(data)
    },
    onSuccess: (_d, status) => {
      message.success(`${status} 처리했습니다.`)
      refresh()
    },
    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: 'name,asc' })
  }

  const openCreate = () => {
    setEditing(null)
    editForm.setFieldsValue({ name: undefined, phone: undefined, memo: undefined, status: '사용' })
    setOpen(true)
  }

  const openEdit = (row: DeliveryRow) => {
    setEditing(row)
    editForm.setFieldsValue({
      name: row.name,
      phone: row.phone,
      memo: row.memo,
      status: row.status || '사용' })
    setOpen(true)
  }

  const download = async () => {
    const { data } = await client.get(`${apiPrefix()}/deliveries/export`, {
      params: filters,
      responseType: 'blob' })
    const url = URL.createObjectURL(data)
    const a = document.createElement('a')
    a.href = url
    a.download = '배송처관리.csv'
    a.click()
    URL.revokeObjectURL(url)
  }

  const columns = useMemo(() => [
    {
      title: '상태',
      dataIndex: 'status',
      width: 80,
      align: 'center' as const,
      render: (v: string) => <span className={v === '미사용' ? 'farebox-cancelled' : ''}>{v}</span> },
    { title: '업체명', dataIndex: 'name', sorter: true },
    { title: '연락처', dataIndex: 'phone', width: 160, align: 'center' as const },
    { title: '비고', dataIndex: 'memo', width: 200, ellipsis: true },
    { title: '등록일', dataIndex: 'createdAt', width: 120, align: 'center' as const, sorter: true },
    {
      title: '관리',
      key: 'manage',
      width: 80,
      align: 'center' as const,
      render: (_: unknown, row: DeliveryRow) => (
        <Button type="primary" size="small" className="staff-manage-btn" icon={<FileTextOutlined />} onClick={() => openEdit(row)} />
      ) },
  ], [])

  return (
    <div className="stock-page delivery-page">
      <div className="stock-title">
        <div>
          <h2><SettingOutlined style={{ marginRight: 8 }} />배송처관리</h2>
          <p>거래하고 있는 배송처를 등록 혹은 관리하실 수 있습니다.</p>
        </div>
        <Space className="stock-title-actions" wrap>
          <Button
            className="farebox-gray-btn"
            disabled={!selected.length}
            loading={statusMut.isPending}
            onClick={() => {
              if (!selected.length) { message.warning('항목을 선택하세요.'); return }
              statusMut.mutate('사용')
            }}
          >
            사용
          </Button>
          <Button
            className="farebox-gray-btn"
            disabled={!selected.length}
            loading={statusMut.isPending}
            onClick={() => {
              if (!selected.length) { message.warning('항목을 선택하세요.'); return }
              statusMut.mutate('미사용')
            }}
          >
            미사용
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>배송처 등록</Button>
        </Space>
      </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-120" options={['업체명', '연락처', '비고'].map((v) => ({ value: v, label: v }))} />
            </Form.Item>
            <Form.Item name="keyword">
              <Input className="w-180" 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>
          <Button type="link" icon={<FileTextOutlined />} onClick={download}>엑셀다운로드</Button>
        </div>
        <CareTable
          size="small"
          loading={query.isLoading}
          rowKey="id"
          dataSource={query.data?.list}
          columns={columns}
          bordered
          rowSelection={{
            selectedRowKeys: selected,
            onChange: (keys) => setSelected(keys.map(Number)) }}
          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
            setFilters((prev) => ({
              ...prev,
              sort: `${String(s.field)},${s.order === 'ascend' ? 'asc' : 'desc'}` }))
          }}
          locale={{ emptyText: '배송처가 없습니다.' }}
        />
      </Card>

      <Modal
        title={editing ? '배송처 수정' : '배송처 등록'}
        open={open}
        onCancel={() => { setOpen(false); setEditing(null) }}
        footer={null}
        width={460}
        destroyOnHidden
        centered
      >
        <Form
          form={editForm}
          labelCol={{ flex: '88px' }}
          wrapperCol={{ flex: 1 }}
          labelAlign="left"
          colon={false}
          onFinish={(values) => saveMut.mutate(values)}
        >
          <Form.Item name="name" label="업체명" rules={[{ required: true, message: '업체명을 입력하세요.' }]}>
            <Input placeholder="업체명을 입력하세요" />
          </Form.Item>
          <Form.Item name="phone" label="연락처">
            <Input placeholder="1588-0000" />
          </Form.Item>
          <Form.Item name="status" label="상태">
            <Select options={['사용', '미사용'].map((v) => ({ value: v, label: v }))} />
          </Form.Item>
          <Form.Item name="memo" label="비고">
            <Input.TextArea rows={2} />
          </Form.Item>
          <div className="sms-send-footer">
            <Button type="primary" htmlType="submit" loading={saveMut.isPending} icon={<EditOutlined />}>
              {editing ? '수정합니다' : '등록'}
            </Button>
            <Button onClick={() => { setOpen(false); setEditing(null) }}>취소</Button>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
