import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Plus, Trash2 } from 'lucide-react'
import { api } from '@/lib/api'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'
import { Button } from '@/components/Button'
import { Modal } from '@/components/Modal'
import { Field, TextInput, Select, Checkbox } from '@/components/Field'
import { useCatalogList, useCatalogMutations } from '@/lib/useCatalog'
import type { PagedResult, RetailPoint, Store } from '@/lib/types'

const URL = '/api/catalog/retail-points'

interface Form {
  id?: string
  name: string
  code: string
  storeId: string
  address: string
  phone: string
  fiscalSerial: string
  fiscalRegNumber: string
  isActive: boolean
}

const blankForm = (storeId: string): Form => ({
  name: '', code: '', storeId, address: '', phone: '',
  fiscalSerial: '', fiscalRegNumber: '', isActive: true,
})

export function RetailPointsPage() {
  const { data, isLoading, page, setPage, search, setSearch, sortKey, sortOrder, setSort } = useCatalogList<RetailPoint>(URL)
  const { create, update, remove } = useCatalogMutations(URL, URL)
  const [form, setForm] = useState<Form | null>(null)

  const stores = useQuery({
    queryKey: ['stores-lookup'],
    queryFn: async () => (await api.get<PagedResult<Store>>('/api/catalog/stores?pageSize=500')).data.items,
    staleTime: 60_000,
  })

  const save = async () => {
    if (!form) return
    const { id, ...payload } = form
    if (id) await update.mutateAsync({ id, input: payload })
    else await create.mutateAsync(payload)
    setForm(null)
  }

  const firstStore = stores.data?.[0]?.id ?? ''

  return (
    <>
      <ListPageShell
        title="Кассы"
        description="Кассовые точки продаж. Каждая привязана к складу, с которого списывается товар."
        actions={
          <>
            <SearchBar value={search} onChange={setSearch} />
            <Button onClick={() => setForm(blankForm(firstStore))} disabled={!firstStore}>
              <Plus className="w-4 h-4" /> Добавить
            </Button>
          </>
        }
        footer={data && data.total > 0 && (
          <Pagination page={page} pageSize={data.pageSize} total={data.total} onPageChange={setPage} />
        )}
      >
        <DataTable
          rows={data?.items ?? []}
          isLoading={isLoading}
          rowKey={(r) => r.id}
          sortKey={sortKey}
          sortOrder={sortOrder}
          onSortChange={setSort}
          onRowClick={(r) => setForm({
            id: r.id, name: r.name, code: r.code ?? '', storeId: r.storeId,
            address: r.address ?? '', phone: r.phone ?? '',
            fiscalSerial: r.fiscalSerial ?? '', fiscalRegNumber: r.fiscalRegNumber ?? '',
            isActive: r.isActive,
          })}
          columns={[
            { header: 'Название', sortKey: 'name', cell: (r) => r.name },
            { header: 'Код', width: '120px', sortKey: 'code', cell: (r) => <span className="font-mono">{r.code ?? '—'}</span> },
            { header: 'Склад', sortKey: 'store', cell: (r) => r.storeName ?? '—' },
            { header: 'Адрес', sortKey: 'address', cell: (r) => r.address ?? '—' },
            { header: 'ККМ', width: '140px', cell: (r) => r.fiscalSerial ?? '—' },
            { header: 'Активна', width: '100px', sortKey: 'isActive', cell: (r) => r.isActive ? '✓' : '—' },
          ]}
        />
      </ListPageShell>

      <Modal
        open={!!form}
        onClose={() => setForm(null)}
        title={form?.id ? 'Редактировать кассу' : 'Новая касса'}
        footer={
          <>
            {form?.id && (
              <Button variant="danger" size="sm" onClick={async () => {
                if (confirm('Удалить кассу?')) {
                  await remove.mutateAsync(form.id!)
                  setForm(null)
                }
              }}>
                <Trash2 className="w-4 h-4" /> Удалить
              </Button>
            )}
            <Button variant="secondary" onClick={() => setForm(null)}>Отмена</Button>
            <Button onClick={save} disabled={!form?.name || !form.storeId}>Сохранить</Button>
          </>
        }
      >
        {form && (
          <div className="space-y-3">
            <div className="grid grid-cols-2 gap-3">
              <Field label="Название">
                <TextInput value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
              </Field>
              <Field label="Код">
                <TextInput value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value })} />
              </Field>
            </div>
            <Field label="Склад">
              <Select value={form.storeId} onChange={(e) => setForm({ ...form, storeId: e.target.value })}>
                {stores.data?.map((s) => (
                  <option key={s.id} value={s.id}>{s.name}</option>
                ))}
              </Select>
            </Field>
            <Field label="Адрес">
              <TextInput value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
            </Field>
            <Field label="Телефон">
              <TextInput value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Серийный № ККМ">
                <TextInput value={form.fiscalSerial} onChange={(e) => setForm({ ...form, fiscalSerial: e.target.value })} />
              </Field>
              <Field label="Рег. № в ОФД">
                <TextInput value={form.fiscalRegNumber} onChange={(e) => setForm({ ...form, fiscalRegNumber: e.target.value })} />
              </Field>
            </div>
            <Checkbox label="Активна" checked={form.isActive} onChange={(v) => setForm({ ...form, isActive: v })} />
          </div>
        )}
      </Modal>
    </>
  )
}
