import { useState } from 'react'
import { Plus, Trash2 } from 'lucide-react'
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, Checkbox } from '@/components/Field'
import { useCatalogList, useCatalogMutations } from '@/lib/useCatalog'
import { type Store } from '@/lib/types'

const URL = '/api/catalog/stores'

interface Form {
  id?: string
  name: string
  code: string
  address: string
  phone: string
  managerName: string
  isMain: boolean
  isActive: boolean
}

const blankForm: Form = {
  name: '', code: '', address: '', phone: '',
  managerName: '', isMain: false, isActive: true,
}

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

  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)
  }

  return (
    <>
      <ListPageShell
        title="Склады"
        description="Физические места хранения товара."
        actions={
          <>
            <SearchBar value={search} onChange={setSearch} />
            <Button onClick={() => setForm(blankForm)}><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 ?? '',
            address: r.address ?? '', phone: r.phone ?? '', managerName: r.managerName ?? '',
            isMain: r.isMain, 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: 'address', cell: (r) => r.address ?? '—' },
            { header: 'Основной', width: '110px', sortKey: 'isMain', cell: (r) => r.isMain ? '✓' : '—' },
            { 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}>Сохранить</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="Адрес">
              <TextInput value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Телефон">
                <TextInput value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
              </Field>
              <Field label="Заведующий">
                <TextInput value={form.managerName} onChange={(e) => setForm({ ...form, managerName: e.target.value })} />
              </Field>
            </div>
            <Checkbox label="Основной склад организации" checked={form.isMain} onChange={(v) => setForm({ ...form, isMain: v })} />
            <Checkbox label="Активен" checked={form.isActive} onChange={(v) => setForm({ ...form, isActive: v })} />
          </div>
        )}
      </Modal>
    </>
  )
}
