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,
  Tag,
  Typography,
  message } from 'antd'
import CareTable from '../../components/CareTable'
import {
  EditOutlined, FileTextOutlined, MailOutlined, PlusOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'

type StaffRow = {
  id: number
  status?: string
  active?: boolean
  staffPermission?: string
  userid?: string
  name?: string
  phone?: string
  assignedOutNames?: string
  loginCount?: number
  lastLoginAt?: string
  createdAt?: string
  memo?: string
  isOwner?: boolean
}

type StaffData = {
  total: number
  list: StaffRow[]
}

const permissions = ['대표', '총괄', '재고', '개통', '영업', '딜러']

export default function StaffManagePage() {
  const qc = useQueryClient()
  const [form] = Form.useForm()
  const [editForm] = Form.useForm()
  const [memoForm] = Form.useForm()
  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<StaffRow | null>(null)
  const [memoOpen, setMemoOpen] = useState(false)
  const [memoTarget, setMemoTarget] = useState<StaffRow | null>(null)
  const [selected, setSelected] = useState<number[]>([])
  const [filters, setFilters] = useState<Record<string, unknown>>({
    page: 0,
    size: 15,
    sort: 'createdAt,asc' })

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

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

  const saveMut = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const body = {
        ...values,
        assignedOutNames: Array.isArray(values.assignedOutNames)
          ? (values.assignedOutNames as string[]).join(',')
          : values.assignedOutNames }
      if (editing?.id) {
        const { data } = await client.put(`${apiPrefix()}/staff/${editing.id}`, body)
        return unwrap(data)
      }
      const { data } = await client.post(`${apiPrefix()}/staff`, body)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success(editing ? '직원 정보를 수정했습니다.' : '직원을 등록했습니다.')
      setOpen(false)
      setEditing(null)
      editForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

  const memoMut = useMutation({
    mutationFn: async (memo: string) => {
      const { data } = await client.put(`${apiPrefix()}/staff/${memoTarget!.id}`, { memo })
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('비고를 저장했습니다.')
      setMemoOpen(false)
      setMemoTarget(null)
      memoForm.resetFields()
      refresh()
    },
    onError: (e: Error) => message.error(e.message) })

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

  const onReset = () => {
    form.setFieldsValue({ status: undefined, keyword: undefined, size: 15 })
    setFilters({ page: 0, size: 15, sort: 'createdAt,asc' })
  }

  const openCreate = () => {
    setEditing(null)
    editForm.setFieldsValue({
      userid: undefined,
      password: undefined,
      name: undefined,
      phone: undefined,
      staffPermission: '영업',
      status: '사용',
      assignedOutNames: undefined })
    setOpen(true)
  }

  const openEdit = (row: StaffRow) => {
    setEditing(row)
    editForm.setFieldsValue({
      userid: row.userid,
      password: undefined,
      name: row.name,
      phone: row.phone,
      staffPermission: row.staffPermission,
      status: row.status || '사용',
      assignedOutNames: row.assignedOutNames
        ? row.assignedOutNames.split(',').map((s) => s.trim()).filter(Boolean)
        : undefined })
    setOpen(true)
  }

  const openMemo = (row: StaffRow) => {
    setMemoTarget(row)
    memoForm.setFieldsValue({ memo: row.memo })
    setMemoOpen(true)
  }

  const download = async () => {
    const { data } = await client.get(`${apiPrefix()}/staff/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: 70,
      align: 'center' as const,
      render: (v: string) => <span className={v === '중지' ? 'farebox-cancelled' : ''}>{v}</span> },
    { title: '권한', dataIndex: 'staffPermission', width: 80, align: 'center' as const, sorter: true },
    { title: '아이디', dataIndex: 'userid', width: 100, align: 'center' as const, sorter: true },
    { title: '이름', dataIndex: 'name', width: 90, align: 'center' as const, sorter: true },
    { title: '휴대폰', dataIndex: 'phone', width: 130, align: 'center' as const },
    {
      title: '담당출고처',
      dataIndex: 'assignedOutNames',
      width: 220,
      render: (v?: string) => {
        if (!v) return ''
        return (
          <div className="staff-out-tags">
            {v.split(',').map((name) => name.trim()).filter(Boolean).map((name) => (
              <span key={name} className="staff-out-tag">
                <Tag className="staff-assign-tag">지정</Tag>
                <span>{name}</span>
              </span>
            ))}
          </div>
        )
      } },
    {
      title: '접속수',
      dataIndex: 'loginCount',
      width: 90,
      align: 'right' as const,
      sorter: true,
      render: (v?: number) => (v == null ? '0' : Number(v).toLocaleString()) },
    { title: '최종접속', dataIndex: 'lastLoginAt', width: 110, align: 'center' as const, sorter: true },
    { title: '등록일', dataIndex: 'createdAt', width: 110, align: 'center' as const, sorter: true },
    {
      title: '비고',
      key: 'memo',
      width: 60,
      align: 'center' as const,
      render: (_: unknown, row: StaffRow) => (
        <Button
          type="text"
          size="small"
          icon={<MailOutlined style={{ color: row.memo ? '#1677ff' : '#94a3b8' }} />}
          onClick={() => openMemo(row)}
        />
      ) },
    {
      title: '관리',
      key: 'manage',
      width: 70,
      align: 'center' as const,
      render: (_: unknown, row: StaffRow) => (
        <Button type="primary" size="small" className="staff-manage-btn" icon={<FileTextOutlined />} onClick={() => openEdit(row)} />
      ) },
  ], [])

  return (
    <div className="stock-page staff-page">
      <div className="stock-title">
        <div>
          <h2><SettingOutlined style={{ marginRight: 8 }} />직원관리</h2>
          <p>매장 직원의 계정을 추가로 등록 혹은 관리하실 수 있습니다.</p>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>직원 등록</Button>
      </div>

      <Card className="stock-filter-card" size="small">
        <Form
          form={form}
          layout="inline"
          className="farebox-filter"
          initialValues={{ size: 15 }}
          onFinish={onSearch}
        >
          <div className="farebox-filter-row">
            <Form.Item name="status">
              <Select
                allowClear
                placeholder="상태"
                className="w-110"
                options={['사용', '중지'].map((v) => ({ value: v, label: v }))}
              />
            </Form.Item>
            <Form.Item name="keyword">
              <Input className="w-180" allowClear placeholder="이름/아이디" />
            </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)),
            getCheckboxProps: (row) => ({
              disabled: !!row.isOwner,
              style: row.isOwner ? { display: 'none' } : undefined }),
            renderCell: (_checked, row, _index, node) => (
              row.isOwner ? <span>-</span> : node
            ) }}
          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'}` }))
          }}
          scroll={{ x: 1300 }}
          locale={{ emptyText: '직원 정보가 없습니다.' }}
        />
      </Card>

      <Modal
        title={editing ? '직원 수정' : '직원 등록'}
        open={open}
        onCancel={() => { setOpen(false); setEditing(null) }}
        footer={null}
        width={520}
        destroyOnHidden
        centered
      >
        <Form
          form={editForm}
          labelCol={{ flex: '100px' }}
          wrapperCol={{ flex: 1 }}
          labelAlign="left"
          colon={false}
          onFinish={(values) => saveMut.mutate(values)}
        >
          <Form.Item name="userid" label="아이디" rules={[{ required: true, message: '아이디를 입력하세요.' }]}>
            <Input disabled={!!editing} />
          </Form.Item>
          <Form.Item
            name="password"
            label="비밀번호"
            rules={editing ? [] : [{ required: true, message: '비밀번호를 입력하세요.' }]}
          >
            <Input.Password placeholder={editing ? '변경 시에만 입력' : undefined} />
          </Form.Item>
          <Form.Item name="name" label="이름" rules={[{ required: true, message: '이름을 입력하세요.' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="phone" label="휴대폰">
            <Input placeholder="010-0000-0000" />
          </Form.Item>
          <Form.Item name="staffPermission" label="권한" rules={[{ required: true, message: '권한을 선택하세요.' }]}>
            <Select
              options={permissions.map((v) => ({ value: v, label: v }))}
              disabled={!!editing?.isOwner}
            />
          </Form.Item>
          <Form.Item name="status" label="상태">
            <Select options={['사용', '중지'].map((v) => ({ value: v, label: v }))} />
          </Form.Item>
          <Form.Item name="assignedOutNames" label="담당출고처">
            <Select
              mode="tags"
              placeholder="출고처명 입력 후 Enter"
              tokenSeparators={[',']}
            />
          </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>

      <Modal
        title="비고"
        open={memoOpen}
        onCancel={() => { setMemoOpen(false); setMemoTarget(null) }}
        footer={null}
        width={420}
        destroyOnHidden
        centered
      >
        <Form form={memoForm} layout="vertical" onFinish={(values) => memoMut.mutate(String(values.memo ?? ''))}>
          <Form.Item name="memo" label={`${memoTarget?.name ?? ''} (${memoTarget?.userid ?? ''})`}>
            <Input.TextArea rows={4} placeholder="비고를 입력하세요" />
          </Form.Item>
          <div className="sms-send-footer">
            <Button type="primary" htmlType="submit" loading={memoMut.isPending}>저장</Button>
            <Button onClick={() => { setMemoOpen(false); setMemoTarget(null) }}>취소</Button>
          </div>
        </Form>
      </Modal>
    </div>
  )
}
