import { useEffect, useState } from 'react'
import { Form, Input, Popover, message } from 'antd'
import { LockOutlined, PoweroffOutlined, UserOutlined } from '@ant-design/icons'
import client, { apiPrefix, unwrap, type ApiResponse } from '../api/client'
import Modal from './DraggableModal'

export type AccountProfile = {
  name: string
  userid: string
  staffPermission: string
  orgLabel: string
  memberCount: number
  expireDate: string
  remainDays: number
}

type Props = {
  onLogout: () => void
}

function formatExpireKo(iso: string) {
  const [y, m, d] = iso.split('-')
  if (!y || !m || !d) return iso
  return `${y}년 ${Number(m)}월 ${Number(d)}일`
}

export default function AccountPopover({ onLogout }: Props) {
  const [open, setOpen] = useState(false)
  const [profile, setProfile] = useState<AccountProfile | null>(null)
  const [pwOpen, setPwOpen] = useState(false)
  const [pwLoading, setPwLoading] = useState(false)
  const [form] = Form.useForm()

  useEffect(() => {
    if (!open) return
    let cancelled = false
    client
      .get<ApiResponse<AccountProfile>>(`${apiPrefix()}/homes/account-profile`)
      .then(({ data }) => {
        if (!cancelled) setProfile(unwrap(data))
      })
      .catch(() => {
        if (cancelled) return
        setProfile({
          name: localStorage.getItem('userName') || '사용자',
          userid: localStorage.getItem('userid') || '',
          staffPermission: localStorage.getItem('staffPermission') || '',
          orgLabel: '데모',
          memberCount: 0,
          expireDate: '2030-12-31',
          remainDays: 0,
        })
      })
    return () => { cancelled = true }
  }, [open])

  const openPassword = () => {
    setOpen(false)
    form.resetFields()
    setPwOpen(true)
  }

  const submitPassword = async () => {
    try {
      const values = await form.validateFields()
      setPwLoading(true)
      const { data } = await client.put<ApiResponse>(`${apiPrefix()}/homes/password`, {
        currentPassword: values.currentPassword,
        newPassword: values.newPassword,
      })
      unwrap(data)
      message.success('비밀번호를 변경했습니다.')
      setPwOpen(false)
      form.resetFields()
    } catch (e) {
      if (e && typeof e === 'object' && 'errorFields' in e) return
      message.error(e instanceof Error ? e.message : '비밀번호 변경에 실패했습니다.')
    } finally {
      setPwLoading(false)
    }
  }

  const p = profile
  const remain = p?.remainDays ?? 0
  const remainText = remain >= 0 ? `${remain}일 남았습니다.` : `${Math.abs(remain)}일 지났습니다.`

  const content = (
    <div className="account-popover">
      <div className="account-popover-head">
        <div className="account-popover-name">{p?.name || '…'}</div>
        <div className="account-popover-sub">
          {p ? `${p.orgLabel} / ${p.staffPermission}` : '…'}
        </div>
      </div>
      <div className="account-popover-meta">
        <div className="account-popover-row">
          <span className="account-popover-label">계정</span>
          <span className="account-popover-value">{p?.userid || '…'}</span>
        </div>
        <div className="account-popover-row">
          <span className="account-popover-label">직원</span>
          <span className="account-popover-value">{p ? `${p.memberCount}명` : '…'}</span>
        </div>
      </div>
      <div className="account-popover-expire">
        <div className="account-popover-expire-title">이용만료일</div>
        <div className="account-popover-expire-date">
          {p ? formatExpireKo(p.expireDate) : '…'}
        </div>
        <div className="account-popover-expire-remain">{p ? remainText : ''}</div>
      </div>
      <div className="account-popover-actions">
        <button type="button" className="account-popover-action" onClick={openPassword}>
          <LockOutlined />
          <span>비밀번호변경</span>
        </button>
        <button
          type="button"
          className="account-popover-action"
          onClick={() => {
            setOpen(false)
            onLogout()
          }}
        >
          <PoweroffOutlined />
          <span>로그아웃</span>
        </button>
      </div>
    </div>
  )

  return (
    <>
      <Popover
        trigger="click"
        open={open}
        onOpenChange={setOpen}
        placement="bottomRight"
        arrow={false}
        overlayClassName="account-popover-overlay"
        content={content}
      >
        <button type="button" className={`header-icon-btn${open ? ' active' : ''}`} aria-label="프로필">
          <UserOutlined />
        </button>
      </Popover>

      <Modal
        title="비밀번호변경"
        open={pwOpen}
        onCancel={() => setPwOpen(false)}
        onOk={() => void submitPassword()}
        okText="변경"
        cancelText="취소"
        confirmLoading={pwLoading}
        destroyOnClose
        width={400}
      >
        <Form form={form} layout="vertical" className="account-pw-form" requiredMark={false}>
          <Form.Item
            name="currentPassword"
            label="현재 비밀번호"
            rules={[{ required: true, message: '현재 비밀번호를 입력하세요.' }]}
          >
            <Input.Password autoComplete="current-password" />
          </Form.Item>
          <Form.Item
            name="newPassword"
            label="새 비밀번호"
            rules={[
              { required: true, message: '새 비밀번호를 입력하세요.' },
              { pattern: /^[A-Za-z0-9]{4,20}$/, message: '영문, 숫자 4~20자입니다.' },
            ]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="새 비밀번호 확인"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '새 비밀번호 확인을 입력하세요.' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) return Promise.resolve()
                  return Promise.reject(new Error('새 비밀번호 확인이 일치하지 않습니다.'))
                },
              }),
            ]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
