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, Select, NumberInput } from '@/components/Field'
import { useCatalogList, useCatalogMutations } from '@/lib/useCatalog'
import { useCurrencies } from '@/lib/useLookups'
import type { Country } from '@/lib/types'

const URL = '/api/catalog/countries'

interface Form {
  id?: string
  code: string
  name: string
  defaultCurrencyId: string | null
  vatRate: number
}

const blank: Form = { code: '', name: '', defaultCurrencyId: null, vatRate: 0 }

export function CountriesPage() {
  const { data, isLoading, page, setPage, search, setSearch, sortKey, sortOrder, setSort } = useCatalogList<Country>(URL)
  const { create, update, remove } = useCatalogMutations(URL, URL)
  const currencies = useCurrencies()
  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(blank)}><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, code: r.code, name: r.name,
            defaultCurrencyId: r.defaultCurrencyId, vatRate: r.vatRate,
          })}
          columns={[
            { header: 'Код', width: '80px', sortKey: 'code', cell: (r) => <span className="font-mono">{r.code}</span> },
            { header: 'Название', sortKey: 'name', cell: (r) => r.name },
            { header: 'Валюта', width: '120px', sortKey: 'currency', cell: (r) => r.defaultCurrencyCode ? `${r.defaultCurrencyCode} ${r.defaultCurrencySymbol ?? ''}` : '—' },
            { header: 'НДС', width: '100px', className: 'text-right', sortKey: 'vatRate', cell: (r) => `${r.vatRate.toFixed(2)}%` },
          ]}
        />
      </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?.code || !form?.name}>Сохранить</Button>
          </>
        }
      >
        {form && (
          <div className="space-y-3">
            <Field label="ISO-код (2 буквы)">
              <TextInput value={form.code} maxLength={2} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase() })} />
            </Field>
            <Field label="Название">
              <TextInput value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </Field>
            <div className="grid grid-cols-2 gap-3">
              <Field label="Валюта">
                <Select
                  value={form.defaultCurrencyId ?? ''}
                  onChange={(e) => setForm({ ...form, defaultCurrencyId: e.target.value || null })}
                >
                  <option value="">—</option>
                  {currencies.data?.map((c) => <option key={c.id} value={c.id}>{c.code} ({c.symbol})</option>)}
                </Select>
              </Field>
              <Field label="Ставка НДС, %">
                <NumberInput
                  value={form.vatRate}
                  onChange={(n) => setForm({ ...form, vatRate: n ?? 0 })}
                />
              </Field>
            </div>
          </div>
        )}
      </Modal>
    </>
  )
}
