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

type ManagerInfo = { name?: string; phone?: string }
type LoginBlock = { mode?: 'none' | 'block_staff' }
type AccessIps = { enabled?: boolean; ips?: string[] }
type ContractSetting = {
  autoRegisterCustomer?: boolean
  defaultMonthsInternet?: number
  defaultMonthsHome?: number
  requireAgency?: boolean
  autoCalcSettle?: boolean
  allowWithdraw?: boolean
}

type HomesPreference = {
  manager?: ManagerInfo
  loginBlock?: LoginBlock
  accessIps?: AccessIps
  contract?: ContractSetting
  incentiveRate?: number
  autoInvoice?: boolean
}

const TAB_KEYS = [
  { key: 'manager', label: '담당자정보 설정' },
  { key: 'loginBlock', label: '로그인차단 설정' },
  { key: 'accessIp', label: '접속아이피 설정' },
  { key: 'contract', label: '계약 설정' },
] as const

type TabKey = (typeof TAB_KEYS)[number]['key']

const splitPhone = (phone?: string) => {
  const digits = String(phone || '').replace(/\D/g, '')
  if (digits.length >= 10) {
    return {
      p1: digits.slice(0, 3),
      p2: digits.slice(3, digits.length - 4),
      p3: digits.slice(-4) }
  }
  const parts = String(phone || '').split('-')
  return { p1: parts[0] || '010', p2: parts[1] || '', p3: parts[2] || '' }
}

function SectionHead({ title, desc }: { title: string; desc: string }) {
  return (
    <div className="pref-section-head">
      <h3>{title}</h3>
      <p>{desc}</p>
    </div>
  )
}

export default function SettingPreferencePage() {
  const qc = useQueryClient()
  const [tab, setTab] = useState<TabKey>('manager')
  const [managerForm] = Form.useForm()
  const [loginForm] = Form.useForm()
  const [contractForm] = Form.useForm()
  const [ipInput, setIpInput] = useState('')
  const [localIps, setLocalIps] = useState<string[]>([])
  const [ipEnabled, setIpEnabled] = useState(false)
  const sectionRefs = useRef<Record<TabKey, HTMLDivElement | null>>({
    manager: null,
    loginBlock: null,
    accessIp: null,
    contract: null })

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

  useEffect(() => {
    if (!query.data) return
    const phone = splitPhone(query.data.manager?.phone)
    managerForm.setFieldsValue({
      name: query.data.manager?.name || '',
      phone1: phone.p1 || '010',
      phone2: phone.p2,
      phone3: phone.p3 })
    loginForm.setFieldsValue({
      mode: query.data.loginBlock?.mode || 'none' })
    setLocalIps(query.data.accessIps?.ips || [])
    setIpEnabled(!!query.data.accessIps?.enabled)
    contractForm.setFieldsValue({
      autoRegisterCustomer: query.data.contract?.autoRegisterCustomer ?? true,
      defaultMonthsInternet: query.data.contract?.defaultMonthsInternet ?? 36,
      defaultMonthsHome: query.data.contract?.defaultMonthsHome ?? 60,
      requireAgency: query.data.contract?.requireAgency ?? false,
      autoCalcSettle: query.data.contract?.autoCalcSettle ?? true,
      allowWithdraw: query.data.contract?.allowWithdraw ?? true,
      incentiveRate: query.data.incentiveRate ?? 5,
      autoInvoice: query.data.autoInvoice ?? true })
  }, [query.data, managerForm, loginForm, contractForm])

  const save = useMutation({
    mutationFn: async (patch: HomesPreference) => {
      const { data } = await client.put<ApiResponse<HomesPreference>>(`${apiPrefix()}/homes/preference`, patch)
      return unwrap(data)
    },
    onSuccess: (data) => {
      qc.setQueryData(['homes-preference'], data)
      message.success('적용했습니다.')
    },
    onError: (e: Error) => message.error(e.message) })

  const onTabChange = (key: string) => {
    const k = key as TabKey
    setTab(k)
    sectionRefs.current[k]?.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }

  const saveManager = async () => {
    const v = await managerForm.validateFields()
    const phone = [v.phone1, v.phone2, v.phone3].filter(Boolean).join('-')
    save.mutate({ manager: { name: v.name, phone } })
  }

  const saveLoginBlock = async () => {
    const v = await loginForm.validateFields()
    save.mutate({ loginBlock: { mode: v.mode } })
  }

  const saveAccessIps = () => {
    save.mutate({ accessIps: { enabled: ipEnabled, ips: localIps } })
  }

  const saveContract = async () => {
    const v = await contractForm.validateFields()
    save.mutate({
      contract: {
        autoRegisterCustomer: v.autoRegisterCustomer,
        defaultMonthsInternet: v.defaultMonthsInternet,
        defaultMonthsHome: v.defaultMonthsHome,
        requireAgency: v.requireAgency,
        autoCalcSettle: v.autoCalcSettle,
        allowWithdraw: v.allowWithdraw },
      incentiveRate: v.incentiveRate,
      autoInvoice: v.autoInvoice })
  }

  const addIp = () => {
    const ip = ipInput.trim()
    if (!ip) {
      message.warning('아이피를 입력하세요.')
      return
    }
    if (localIps.includes(ip)) {
      message.warning('이미 등록된 아이피입니다.')
      return
    }
    setLocalIps((prev) => [...prev, ip])
    setIpInput('')
  }

  return (
    <div className="stock-page pref-page homes-pref-page">
      <div className="stock-title">
        <div>
          <h2>
            <SettingOutlined className="product-title-icon" />
            기본설정
          </h2>
          <p>매니저 이용에 필요한 기본적인 설정을 하실 수 있습니다.</p>
        </div>
      </div>

      <Card className="stock-table-card pref-card" size="small" loading={query.isLoading}>
        <Tabs
          className="pref-tabs homes-pref-tabs"
          activeKey={tab}
          onChange={onTabChange}
          items={TAB_KEYS.map((t) => ({ key: t.key, label: t.label }))}
        />

        <div
          ref={(el) => { sectionRefs.current.manager = el }}
          className="pref-section"
          id="pref-manager"
        >
          <SectionHead
            title="담당자정보"
            desc="결제관련 혹은 알림/안내 등의 연락을 받으실 담당자의 정보를 변경하실 수 있습니다."
          />
          <Form form={managerForm} className="pref-form" requiredMark={false}>
            <table className="pref-table homes-pref-table">
              <thead>
                <tr>
                  <th className="homes-pref-col-label">구분</th>
                  <th>내용</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th>담당자명</th>
                  <td>
                    <Form.Item name="name" rules={[{ required: true, message: '담당자명을 입력하세요.' }]} noStyle>
                      <Input className="pref-input-md" />
                    </Form.Item>
                  </td>
                </tr>
                <tr>
                  <th>연락처</th>
                  <td>
                    <Space size={6}>
                      <Form.Item name="phone1" noStyle>
                        <Input className="pref-phone-input" maxLength={3} />
                      </Form.Item>
                      <Form.Item name="phone2" noStyle>
                        <Input className="pref-phone-input" maxLength={4} />
                      </Form.Item>
                      <Form.Item name="phone3" noStyle>
                        <Input className="pref-phone-input" maxLength={4} />
                      </Form.Item>
                    </Space>
                  </td>
                </tr>
              </tbody>
            </table>
            <div className="pref-actions">
              <Button className="homes-pref-apply" type="primary" loading={save.isPending} onClick={saveManager}>
                적용
              </Button>
            </div>
          </Form>
        </div>

        <div
          ref={(el) => { sectionRefs.current.loginBlock = el }}
          className="pref-section"
          id="pref-loginBlock"
        >
          <SectionHead
            title="로그인차단 설정"
            desc="원하시는 권한의 로그인을 차단하도록 설정하실 수 있습니다."
          />
          <Form form={loginForm} className="pref-form" requiredMark={false}>
            <table className="pref-table homes-pref-table">
              <thead>
                <tr>
                  <th className="homes-pref-col-label">구분</th>
                  <th>내용</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th>로그인 차단권한</th>
                  <td>
                    <Form.Item name="mode" noStyle>
                      <Radio.Group
                        options={[
                          { value: 'none', label: '차단하지 않습니다.' },
                          { value: 'block_staff', label: '총괄, 팀장, 사원을 차단합니다.' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
              </tbody>
            </table>
            <div className="pref-actions">
              <Button className="homes-pref-apply" type="primary" loading={save.isPending} onClick={saveLoginBlock}>
                적용
              </Button>
            </div>
          </Form>
        </div>

        <div
          ref={(el) => { sectionRefs.current.accessIp = el }}
          className="pref-section"
          id="pref-accessIp"
        >
          <SectionHead
            title="접속아이피 설정"
            desc="허용된 아이피에서만 접속하도록 제한할 수 있습니다. 미사용 시 모든 아이피에서 접속 가능합니다."
          />
          <table className="pref-table homes-pref-table">
            <thead>
              <tr>
                <th className="homes-pref-col-label">구분</th>
                <th>내용</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th>접속제한</th>
                <td>
                  <Radio.Group
                    value={ipEnabled}
                    onChange={(e) => setIpEnabled(e.target.value)}
                    options={[
                      { value: false, label: '미사용' },
                      { value: true, label: '사용' },
                    ]}
                  />
                </td>
              </tr>
              <tr>
                <th>아이피 등록</th>
                <td>
                  <Space>
                    <Input
                      className="pref-input-md"
                      placeholder="예: 123.456.789.012"
                      value={ipInput}
                      onChange={(e) => setIpInput(e.target.value)}
                      onPressEnter={addIp}
                    />
                    <Button icon={<PlusOutlined />} onClick={addIp}>
                      추가
                    </Button>
                  </Space>
                </td>
              </tr>
            </tbody>
          </table>
          <CareTable
            className="pref-list-table"
            size="small"
            rowKey="ip"
            pagination={false}
            style={{ marginTop: 12 }}
            dataSource={localIps.map((ip) => ({ ip }))}
            columns={[
              {
                title: 'No',
                width: 60,
                align: 'center' as const,
                render: (_: unknown, __: { ip: string }, i: number) => i + 1 },
              { title: '아이피', dataIndex: 'ip' },
              {
                title: '관리',
                width: 90,
                align: 'center' as const,
                render: (_: unknown, row: { ip: string }) => (
                  <Button
                    size="small"
                    danger
                    onClick={() => setLocalIps((prev) => prev.filter((x) => x !== row.ip))}
                  >
                    삭제
                  </Button>
                ) },
            ]}
            locale={{ emptyText: '등록된 아이피가 없습니다.' }}
          />
          <div className="pref-actions">
            <Button className="homes-pref-apply" type="primary" loading={save.isPending} onClick={saveAccessIps}>
              적용
            </Button>
          </div>
        </div>

        <div
          ref={(el) => { sectionRefs.current.contract = el }}
          className="pref-section"
          id="pref-contract"
        >
          <SectionHead
            title="계약 설정"
            desc="계약 등록·정산 업무에 적용되는 기본 옵션을 설정합니다."
          />
          <Form form={contractForm} className="pref-form" requiredMark={false}>
            <table className="pref-table homes-pref-table">
              <thead>
                <tr>
                  <th className="homes-pref-col-label">구분</th>
                  <th>내용</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th>고객 자동등록</th>
                  <td>
                    <Form.Item name="autoRegisterCustomer" noStyle>
                      <Radio.Group
                        options={[
                          { value: true, label: '계약 시 고객을 자동등록합니다.' },
                          { value: false, label: '자동등록하지 않습니다.' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
                <tr>
                  <th>기본 약정개월(인터넷)</th>
                  <td>
                    <Space>
                      <Form.Item name="defaultMonthsInternet" noStyle>
                        <InputNumber min={1} max={120} className="pref-number" />
                      </Form.Item>
                      <Typography.Text type="secondary">개월</Typography.Text>
                    </Space>
                  </td>
                </tr>
                <tr>
                  <th>기본 약정개월(홈렌탈)</th>
                  <td>
                    <Space>
                      <Form.Item name="defaultMonthsHome" noStyle>
                        <InputNumber min={1} max={120} className="pref-number" />
                      </Form.Item>
                      <Typography.Text type="secondary">개월</Typography.Text>
                    </Space>
                  </td>
                </tr>
                <tr>
                  <th>거래처 필수</th>
                  <td>
                    <Form.Item name="requireAgency" noStyle>
                      <Radio.Group
                        options={[
                          { value: true, label: '필수' },
                          { value: false, label: '선택' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
                <tr>
                  <th>정산금액 자동계산</th>
                  <td>
                    <Form.Item name="autoCalcSettle" noStyle>
                      <Radio.Group
                        options={[
                          { value: true, label: '사용' },
                          { value: false, label: '미사용' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
                <tr>
                  <th>철회 허용</th>
                  <td>
                    <Form.Item name="allowWithdraw" noStyle>
                      <Radio.Group
                        options={[
                          { value: true, label: '허용' },
                          { value: false, label: '미허용' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
                <tr>
                  <th>인센티브율</th>
                  <td>
                    <Space>
                      <Form.Item name="incentiveRate" noStyle>
                        <InputNumber min={0} max={100} className="pref-number" />
                      </Form.Item>
                      <Typography.Text type="secondary">%</Typography.Text>
                    </Space>
                  </td>
                </tr>
                <tr>
                  <th>월말 자동정산서</th>
                  <td>
                    <Form.Item name="autoInvoice" noStyle>
                      <Radio.Group
                        options={[
                          { value: true, label: '사용' },
                          { value: false, label: '미사용' },
                        ]}
                      />
                    </Form.Item>
                  </td>
                </tr>
              </tbody>
            </table>
            <div className="pref-actions">
              <Button className="homes-pref-apply" type="primary" loading={save.isPending} onClick={saveContract}>
                적용
              </Button>
            </div>
          </Form>
        </div>
      </Card>
    </div>
  )
}
