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

type PartnerRow = {
  id: number
  status?: string
  name?: string
  userid?: string
  managerName?: string
  phone?: string
  registeredDate?: string
  memo?: string
  partnerLevel?: string
}

type PartnerResult = {
  total: number
  list: PartnerRow[]
}

export default function SettingPartner2Page() {
  const qc = useQueryClient()
  const [editForm] = Form.useForm()
  const [filters, setFilters] = useState({ page: 0, size: 15, partnerLevel: '2' })
  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<PartnerRow | null>(null)

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

  const refresh = () => {
    qc.invalidateQueries({ queryKey: ['homes-partners-2'] })
  }

  const saveMut = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      if (!editing?.id) throw new Error('하부점을 선택하세요.')
      const payload = {
        partnerLevel: '2',
        name: values.name ?? editing.name,
        userid: values.userid ?? editing.userid,
        managerName: values.managerName ?? editing.managerName,
        phone: values.phone ?? editing.phone,
        memo: values.memo,
        status: values.status || editing.status || '대기' }
      const { data } = await client.put(`${apiPrefix()}/homes/partners/${editing.id}`, payload)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success('적용했습니다.')
      setOpen(false)
      setEditing(null)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const deleteMut = useMutation({
    mutationFn: async (id: number) => {
      const { data } = await client.delete(`${apiPrefix()}/homes/partners/${id}`)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success('삭제했습니다.')
      setOpen(false)
      setEditing(null)
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const openEdit = (row: PartnerRow) => {
    setEditing(row)
    editForm.setFieldsValue({
      name: row.name,
      userid: row.userid,
      managerName: row.managerName,
      phone: row.phone,
      memo: row.memo,
      status: row.status || '대기' })
    setOpen(true)
  }

  const columns = [
    {
      title: '상태',
      dataIndex: 'status',
      width: 90,
      align: 'center' as const,
      render: (v?: string) => {
        const status = v || '대기'
        const cls =
          status === '승인'
            ? 'partner-status-ok'
            : status === '보류'
              ? 'partner-status-hold'
              : status === '거절'
                ? 'partner-status-deny'
                : 'partner-status-wait'
        return <span className={cls}>{status}</span>
      } },
    {
      title: '업체명',
      dataIndex: 'name',
      width: 180,
      ellipsis: true,
      render: (v?: string) => v || '' },
    {
      title: '아이디',
      dataIndex: 'userid',
      width: 120,
      align: 'center' as const,
      render: (v?: string) => v || '' },
    {
      title: '담당자',
      dataIndex: 'managerName',
      width: 100,
      align: 'center' as const,
      render: (v?: string) => v || '' },
    {
      title: '연락처',
      dataIndex: 'phone',
      width: 130,
      align: 'center' as const,
      render: (v?: string) => v || '' },
    {
      title: '등록일',
      dataIndex: 'registeredDate',
      width: 120,
      align: 'center' as const },
    {
      title: '관리',
      key: 'manage',
      width: 64,
      align: 'center' as const,
      render: (_: unknown, row: PartnerRow) => (
        <Button
          type="primary"
          size="small"
          className="partner-manage-btn"
          icon={<EditOutlined />}
          onClick={() => openEdit(row)}
        />
      ) },
  ]

  return (
    <div className="stock-page partner-page partner2-page">
      <div className="stock-title">
        <div>
          <h2>
            <SettingOutlined className="product-title-icon" />
            하부점관리
          </h2>
          <p>하부점의 연결요청을 승인 및 보류 등 관리하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="stock-table-card" size="small">
        <div className="farebox-table-toolbar">
          <Typography.Text>
            목록 <b>{query.data?.total ?? 0}</b>
          </Typography.Text>
        </div>
        <CareTable
          size="small"
          loading={query.isLoading}
          rowKey="id"
          dataSource={query.data?.list}
          columns={columns}
          bordered
          pagination={{
            current: filters.page + 1,
            pageSize: filters.size,
            total: query.data?.total ?? 0,
            showSizeChanger: false,
            onChange: (page) => setFilters((prev) => ({ ...prev, page: page - 1 })) }}
          locale={{ emptyText: '등록되어 있는 하부점이 없습니다.' }}
        />
      </Card>

      <Modal
        title="하부점 연결요청 관리"
        open={open}
        onCancel={() => {
          setOpen(false)
          setEditing(null)
        }}
        footer={null}
        width={480}
        destroyOnHidden
        centered
      >
        <Form
          form={editForm}
          labelCol={{ flex: '100px' }}
          wrapperCol={{ flex: 1 }}
          labelAlign="left"
          colon={false}
          onFinish={(values) => saveMut.mutate(values)}
        >
          <Form.Item name="name" label="업체명">
            <Input disabled />
          </Form.Item>
          <Form.Item name="userid" label="아이디">
            <Input disabled />
          </Form.Item>
          <Form.Item name="managerName" label="담당자">
            <Input disabled />
          </Form.Item>
          <Form.Item name="phone" label="연락처">
            <Input disabled />
          </Form.Item>
          <Form.Item name="status" label="처리상태" rules={[{ required: true, message: '상태를 선택하세요.' }]}>
            <Radio.Group
              options={[
                { value: '대기', label: '대기' },
                { value: '승인', label: '승인' },
                { value: '보류', label: '보류' },
                { value: '거절', label: '거절' },
              ]}
            />
          </Form.Item>
          <Form.Item name="memo" label="비고">
            <Input.TextArea rows={2} placeholder="처리 메모" />
          </Form.Item>
          <div className="sms-send-footer">
            <Button
              className="partner-submit-btn"
              type="primary"
              htmlType="submit"
              loading={saveMut.isPending}
              icon={<EditOutlined />}
            >
              적용
            </Button>
            <Space>
              {editing ? (
                <Button
                  danger
                  loading={deleteMut.isPending}
                  onClick={() => deleteMut.mutate(editing.id)}
                >
                  삭제
                </Button>
              ) : null}
              <Button
                onClick={() => {
                  setOpen(false)
                  setEditing(null)
                }}
              >
                취소
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
