import { useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Button, Card, Checkbox, Form, Input, InputNumber, Popconfirm, Select, Space, Tabs, message } from 'antd'
import CareTable from '../../components/CareTable'
import {
  AppstoreOutlined, FormOutlined, PlusSquareOutlined, SettingOutlined, SyncOutlined } from '@ant-design/icons'
import Modal from '../../components/DraggableModal'
import client, { apiPrefix, unwrap, type ApiResponse } from '../../api/client'
import { money, options, type PageResult, type Row } from './homesShared'

const CATEGORIES = ['정수기', '공기청정기', '비데', '매트리스', '가전', '기타'] as const
const COMPANIES = ['청호나이스', '코웨이', 'SK매직', 'LG전자', '삼성', '시몬스', '위닉스', '기타']
const MONTH_OPTIONS = [
  { value: 0, label: '무약정' },
  { value: 12, label: '1년(12개월)' },
  { value: 24, label: '2년(24개월)' },
  { value: 36, label: '3년(36개월)' },
  { value: 48, label: '4년(48개월)' },
  { value: 60, label: '5년(60개월)' },
]

function formatMonths(v: unknown) {
  if (v == null || v === '') return '-'
  const months = Number(v)
  if (!months) return '무약정'
  if (months % 12 === 0) return `${months / 12}년(${months}개월)`
  return `${months}개월`
}

export default function ProductHomePage() {
  const qc = useQueryClient()
  const [searchParams] = useSearchParams()
  const [form] = Form.useForm()
  const [policyForm] = Form.useForm()
  const initialCategory = CATEGORIES.includes(searchParams.get('category') as (typeof CATEGORIES)[number])
    ? (searchParams.get('category') as string)
    : '정수기'
  const [category, setCategory] = useState<string>(initialCategory)
  const [page, setPage] = useState(0)
  const [size, setSize] = useState(15)
  const [selected, setSelected] = useState<number[]>([])
  const [open, setOpen] = useState(false)
  const [editing, setEditing] = useState<Row | null>(null)
  const [policyTarget, setPolicyTarget] = useState<Row | null>(null)

  const filters = useMemo(
    () => ({ kind: 'HOME', category, page, size }),
    [category, page, size],
  )

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

  const policies = useQuery({
    queryKey: ['homes/product-policies', policyTarget?.id],
    queryFn: async () => {
      const { data } = await client.get<ApiResponse<{ list: Row[] }>>(
        `${apiPrefix()}/homes/products/${policyTarget!.id}/policies`,
      )
      return unwrap(data)
    },
    enabled: Boolean(policyTarget) })

  const save = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const payload = { kind: 'HOME', ...values }
      if (editing) {
        const { data } = await client.put(`${apiPrefix()}/homes/products/${editing.id}`, payload)
        return unwrap(data)
      }
      const { data } = await client.post(`${apiPrefix()}/homes/products`, payload)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success(editing ? '수정했습니다.' : '등록했습니다.')
      setOpen(false)
      setEditing(null)
      form.resetFields()
      qc.invalidateQueries({ queryKey: ['homes/products'] })
    },
    onError: (e: Error) => message.error(e.message) })

  const remove = useMutation({
    mutationFn: async (id: number) => {
      const { data } = await client.delete(`${apiPrefix()}/homes/products/${id}`)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('삭제했습니다.')
      qc.invalidateQueries({ queryKey: ['homes/products'] })
    },
    onError: (e: Error) => message.error(e.message) })

  const sync = useMutation({
    mutationFn: async () => {
      const { data } = await client.post<ApiResponse<{ added: number }>>(`${apiPrefix()}/homes/products/sync`, { kind: 'HOME' })
      return unwrap(data)
    },
    onSuccess: (res) => {
      message.success(`기본상품을 동기화했습니다. (+${res?.added ?? 0})`)
      qc.invalidateQueries({ queryKey: ['homes/products'] })
    },
    onError: (e: Error) => message.error(e.message) })

  const addPolicy = useMutation({
    mutationFn: async (values: Record<string, unknown>) => {
      const { data } = await client.post(`${apiPrefix()}/homes/products/${policyTarget!.id}/policies`, values)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('정책을 등록했습니다.')
      policyForm.resetFields()
      policyForm.setFieldsValue({ amount: 100000 })
      qc.invalidateQueries({ queryKey: ['homes/product-policies', policyTarget?.id] })
      qc.invalidateQueries({ queryKey: ['homes/products'] })
    },
    onError: (e: Error) => message.error(e.message) })

  const removePolicy = useMutation({
    mutationFn: async (id: number) => {
      const { data } = await client.delete(`${apiPrefix()}/homes/products/policies/${id}`)
      return unwrap(data)
    },
    onSuccess: () => {
      message.success('정책을 삭제했습니다.')
      qc.invalidateQueries({ queryKey: ['homes/product-policies', policyTarget?.id] })
      qc.invalidateQueries({ queryKey: ['homes/products'] })
    },
    onError: (e: Error) => message.error(e.message) })

  const openCreate = () => {
    setEditing(null)
    form.resetFields()
    form.setFieldsValue({ category, months: 60 })
    setOpen(true)
  }

  const openEdit = (row: Row) => {
    setEditing(row)
    form.setFieldsValue({
      category: row.category,
      company: row.company,
      name: row.name,
      model: row.model,
      months: row.months ?? 0,
      memo: row.memo })
    setOpen(true)
  }

  const counts = query.data?.counts
  const list = query.data?.list || []

  const columns = [
    {
      title: (
        <Checkbox
          checked={list.length > 0 && selected.length === list.length}
          indeterminate={selected.length > 0 && selected.length < list.length}
          onChange={(e) => setSelected(e.target.checked ? list.map((r) => r.id) : [])}
        />
      ),
      width: 48,
      align: 'center' as const,
      render: (_: unknown, row: Row) => (
        <Checkbox
          checked={selected.includes(row.id)}
          onChange={(e) => {
            setSelected((prev) => (e.target.checked ? [...prev, row.id] : prev.filter((id) => id !== row.id)))
          }}
        />
      ) },
    { title: '회사', dataIndex: 'company', width: 100 },
    { title: '상품명', dataIndex: 'name', width: 160, ellipsis: true },
    { title: '모델명', dataIndex: 'model', width: 140, ellipsis: true, render: (v: unknown) => v || '' },
    {
      title: '기본약정',
      dataIndex: 'months',
      width: 130,
      render: formatMonths },
    { title: '비고', dataIndex: 'memo', width: 140, ellipsis: true, render: (v: unknown) => v || '' },
    {
      title: '정책설정',
      width: 130,
      align: 'center' as const,
      render: (_: unknown, row: Row) => {
        const count = Number(row.policyCount || 0)
        return (
          <Button
            type="primary"
            size="small"
            className="product-policy-btn"
            onClick={() => {
              setPolicyTarget(row)
              policyForm.setFieldsValue({ amount: row.policyAmount || 100000 })
            }}
          >
            {count > 0 ? `정책설정(${count})` : '정책설정'}
          </Button>
        )
      } },
    {
      title: '관리',
      width: 64,
      align: 'center' as const,
      render: (_: unknown, row: Row) => (
        <Button
          type="primary"
          size="small"
          className="product-manage-btn"
          icon={<FormOutlined />}
          onClick={() => openEdit(row)}
        />
      ) },
  ]

  return (
    <div className="stock-page product-internet-page">
      <div className="stock-title">
        <div>
          <h2>
            <AppstoreOutlined className="product-title-icon" />
            홈렌탈상품
          </h2>
          <p>홈렌탈상품을 등록 및 관리하실 수 있습니다.</p>
        </div>
        <Space>
          <Button icon={<SyncOutlined />} loading={sync.isPending} onClick={() => sync.mutate()}>
            기본상품 동기화
          </Button>
          <Button type="primary" icon={<PlusSquareOutlined />} onClick={openCreate}>
            홈렌탈상품 등록
          </Button>
        </Space>
      </div>

      <Card className="stock-table-card product-internet-card" size="small">
        <div className="product-internet-tabs">
          <Tabs
            activeKey={category}
            onChange={(key) => {
              setCategory(key)
              setPage(0)
              setSelected([])
            }}
            items={CATEGORIES.map((c) => ({
              key: c,
              label: counts?.[c] != null ? `${c} ${counts[c]}` : c }))}
          />
          <div className="product-internet-settings">
            <button type="button" className="product-setting-link" onClick={() => message.info('추가구성품설정(데모)')}>
              <SettingOutlined /> 추가구성품설정
            </button>
          </div>
        </div>

        <CareTable
          rowKey="id"
          size="small"
          loading={query.isLoading}
          dataSource={list}
          columns={columns}
          scroll={{ x: 1000 }}
          pagination={{
            current: page + 1,
            pageSize: size,
            total: query.data?.total || 0,
            showSizeChanger: true,
            pageSizeOptions: ['15', '30', '50', '100'],
            onChange: (p, s) => {
              setPage(p - 1)
              setSize(s)
              setSelected([])
            },
            showTotal: (t) => `총 ${t}건` }}
        />
      </Card>

      <Modal
        title={editing ? '홈렌탈상품 수정' : '홈렌탈상품 등록'}
        open={open}
        onCancel={() => setOpen(false)}
        footer={null}
        width={520}
        destroyOnHidden
        className="product-internet-modal"
      >
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ flex: '100px' }}
          wrapperCol={{ flex: 1 }}
          colon={false}
          onFinish={(values) => save.mutate(values)}
          className="product-internet-form"
        >
          <Form.Item name="category" label="구분" rules={[{ required: true, message: '구분을 선택하세요' }]}>
            <Select options={options([...CATEGORIES])} />
          </Form.Item>
          <Form.Item name="company" label="회사" rules={[{ required: true, message: '회사를 선택하세요' }]}>
            <Select placeholder="- 선택 -" options={options(COMPANIES)} />
          </Form.Item>
          <Form.Item name="name" label="상품명" rules={[{ required: true, message: '상품명을 입력하세요' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="model" label="모델명">
            <Input />
          </Form.Item>
          <Form.Item name="months" label="기본약정">
            <Select placeholder="- 선택 -" allowClear options={MONTH_OPTIONS} />
          </Form.Item>
          <Form.Item name="memo" label="비고">
            <Input />
          </Form.Item>
          <div className="product-modal-footer">
            {editing && (
              <Popconfirm title="이 상품을 삭제할까요?" onConfirm={() => { remove.mutate(editing.id); setOpen(false) }}>
                <Button danger>삭제</Button>
              </Popconfirm>
            )}
            <div className="product-modal-footer-right">
              <Button type="primary" htmlType="submit" loading={save.isPending}>
                {editing ? '수정합니다' : '등록'}
              </Button>
              <Button onClick={() => setOpen(false)}>취소</Button>
            </div>
          </div>
        </Form>
      </Modal>

      <Modal
        title={`정책설정 - ${policyTarget?.name ?? ''}`}
        open={Boolean(policyTarget)}
        onCancel={() => setPolicyTarget(null)}
        footer={null}
        width={640}
        destroyOnHidden
      >
        <Form
          form={policyForm}
          layout="inline"
          className="product-policy-form"
          onFinish={(v) => addPolicy.mutate(v)}
          initialValues={{ amount: 100000 }}
        >
          <Form.Item name="name" label="정책명" rules={[{ required: true, message: '정책명 필수' }]}>
            <Input placeholder="정책명" className="w-150" />
          </Form.Item>
          <Form.Item name="amount" label="금액" rules={[{ required: true, message: '금액 필수' }]}>
            <InputNumber className="w-130" controls={false} addonAfter="원" />
          </Form.Item>
          <Button type="primary" htmlType="submit" loading={addPolicy.isPending}>추가</Button>
        </Form>
        <CareTable
          className="product-policy-table"
          rowKey="id"
          size="small"
          loading={policies.isLoading}
          dataSource={policies.data?.list || []}
          pagination={false}
          columns={[
            { title: '정책명', dataIndex: 'name' },
            {
              title: '금액',
              dataIndex: 'amount',
              align: 'right' as const,
              width: 120,
              render: money },
            {
              title: '관리',
              width: 70,
              align: 'center' as const,
              render: (_: unknown, row: Row) => (
                <Popconfirm title="삭제할까요?" onConfirm={() => removePolicy.mutate(row.id)}>
                  <Button size="small" type="link" danger>삭제</Button>
                </Popconfirm>
              ) },
          ]}
        />
      </Modal>
    </div>
  )
}
