import { useState } from 'react'
import Modal from '../../components/DraggableModal'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Button,
  Card,
  Form,
  Input,
  Space,
  Typography,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import {
  EditOutlined,
  PlusSquareOutlined,
  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[]
}

/** 원본 안내 문구용 잎 아이콘 */
function LeafOutlined({ className }: { className?: string }) {
  return (
    <span className={className} role="img" aria-label="leaf">
      <svg viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor" aria-hidden>
        <path d="M17 8C8 10 5.9 16.17 3.82 21.34l1.89.66.95-2.3c.10.0.1.1.34.01C19 20 22 3 22 3c-1 2-8 2.25-13 3.25S2 11.5 2 13.5s1.75 3.75 1.75 3.75C7 8 17 8 17 8z" />
      </svg>
    </span>
  )
}

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

  const query = useQuery({
    queryKey: ['homes-partners-1', 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-1'] })
  }

  const saveMut = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const payload = {
        partnerLevel: '1',
        name: values.name,
        userid: values.userid,
        managerName: values.managerName,
        phone: values.phone,
        memo: values.memo,
        status: values.status || editing?.status || '대기' }
      if (editing?.id) {
        const { data } = await client.put(`${apiPrefix()}/homes/partners/${editing.id}`, payload)
        return unwrap(data as ApiResponse)
      }
      const { data } = await client.post(`${apiPrefix()}/homes/partners`, payload)
      return unwrap(data as ApiResponse)
    },
    onSuccess: () => {
      message.success(editing ? '수정했습니다.' : '상부점 등록을 신청했습니다.')
      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('삭제했습니다.')
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const openCreate = () => {
    setEditing(null)
    editForm.setFieldsValue({
      name: undefined,
      userid: undefined,
      managerName: undefined,
      phone: undefined,
      memo: undefined,
      status: '대기' })
    setOpen(true)
  }

  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-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 partner1-page">
      <div className="stock-title">
        <div>
          <h2>
            <SettingOutlined className="product-title-icon" />
            상부점관리
          </h2>
          <p>계약자료 전송을 위한 상부점을 등록 혹은 관리하실 수 있습니다.</p>
        </div>
        <Button className="partner-register-btn" type="primary" icon={<PlusSquareOutlined />} onClick={openCreate}>
          상부점 등록
        </Button>
      </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: '등록되어 있는 상부점이 없습니다.' }}
        />
        <div className="partner-note">
          <LeafOutlined className="partner-note-icon" />
          <span>
            상부점에서 승인처리 후 계약자료 전송이 가능합니다. (또한 상부점에서 등록신청을 삭제할 경우 목록에서 제외됩니다.)
          </span>
        </div>
      </Card>

      <Modal
        title={editing ? '상부점 수정' : '상부점 등록'}
        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="업체명" rules={[{ required: true, message: '업체명을 입력하세요.' }]}>
            <Input placeholder="상부점 업체명" />
          </Form.Item>
          <Form.Item name="userid" label="아이디" rules={[{ required: true, message: '아이디를 입력하세요.' }]}>
            <Input placeholder="상부점 아이디" disabled={!!editing} />
          </Form.Item>
          <Form.Item name="managerName" label="담당자">
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="연락처">
            <Input placeholder="010-0000-0000" />
          </Form.Item>
          <Form.Item name="memo" label="비고">
            <Input.TextArea rows={2} />
          </Form.Item>
          <div className="sms-send-footer">
            <Button
              className="partner-submit-btn"
              type="primary"
              htmlType="submit"
              loading={saveMut.isPending}
              icon={<EditOutlined />}
            >
              {editing ? '수정합니다' : '등록'}
            </Button>
            <Space>
              {editing ? (
                <Button
                  danger
                  loading={deleteMut.isPending}
                  onClick={() => {
                    deleteMut.mutate(editing.id)
                    setOpen(false)
                    setEditing(null)
                  }}
                >
                  삭제
                </Button>
              ) : null}
              <Button
                onClick={() => {
                  setOpen(false)
                  setEditing(null)
                }}
              >
                취소
              </Button>
            </Space>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
