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, TextArea, Select } from '@/components/Field'
import { PhoneInput } from '@/components/PhoneInput'
import { useCatalogList, useCatalogMutations } from '@/lib/useCatalog'
import { type Counterparty, type Country, type PagedResult, CounterpartyType } from '@/lib/types'

const URL = '/api/catalog/counterparties'

interface Form {
  id?: string
  name: string
  legalName: string
  type: CounterpartyType
  bin: string
  iin: string
  taxNumber: string
  countryId: string
  address: string
  phone: string
  email: string
  bankName: string
  bankAccount: string
  bik: string
  contactPerson: string
  notes: string
}

const blankForm: Form = {
  name: '', legalName: '', type: CounterpartyType.LegalEntity,
  bin: '', iin: '', taxNumber: '', countryId: '',
  address: '', phone: '', email: '',
  bankName: '', bankAccount: '', bik: '',
  contactPerson: '', notes: '',
}

const typeLabel: Record<CounterpartyType, string> = {
  [CounterpartyType.LegalEntity]: 'Юрлицо',
  [CounterpartyType.Individual]: 'Физлицо',
}

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

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

  const save = async () => {
    if (!form) return
    const { id, countryId, ...rest } = form
    const payload = { ...rest, countryId: countryId || null }
    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} placeholder="Поиск по имени, БИН, ИИН, телефону…" />
            <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, legalName: r.legalName ?? '', type: r.type,
            bin: r.bin ?? '', iin: r.iin ?? '', taxNumber: r.taxNumber ?? '',
            countryId: r.countryId ?? '', address: r.address ?? '', phone: r.phone ?? '', email: r.email ?? '',
            bankName: r.bankName ?? '', bankAccount: r.bankAccount ?? '', bik: r.bik ?? '',
            contactPerson: r.contactPerson ?? '', notes: r.notes ?? '',
          })}
          columns={[
            { header: 'Название', sortKey: 'name', cell: (r) => r.name },
            { header: 'Тип', width: '120px', sortKey: 'type', cell: (r) => typeLabel[r.type] },
            { header: 'БИН/ИИН', width: '140px', cell: (r) => <span className="font-mono">{r.bin ?? r.iin ?? '—'}</span> },
            { header: 'Телефон', width: '160px', sortKey: 'phone', cell: (r) => r.phone ?? '—' },
            { header: 'Страна', width: '120px', sortKey: 'country', cell: (r) => r.countryName ?? '—' },
          ]}
        />
      </ListPageShell>

      <Modal
        open={!!form}
        onClose={() => setForm(null)}
        title={form?.id ? 'Редактировать контрагента' : 'Новый контрагент'}
        width="max-w-3xl"
        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="grid grid-cols-2 gap-3">
            <Field label="Название" className="col-span-2">
              <TextInput value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </Field>
            <Field label="Юридическое название" className="col-span-2">
              <TextInput value={form.legalName} onChange={(e) => setForm({ ...form, legalName: e.target.value })} />
            </Field>
            <Field label="Тип лица">
              <Select value={form.type} onChange={(e) => setForm({ ...form, type: Number(e.target.value) as CounterpartyType })}>
                <option value={CounterpartyType.LegalEntity}>Юрлицо</option>
                <option value={CounterpartyType.Individual}>Физлицо</option>
              </Select>
            </Field>
            <Field label="БИН (юрлицо РК)">
              <TextInput value={form.bin} onChange={(e) => setForm({ ...form, bin: e.target.value })} placeholder="12 цифр" maxLength={12} inputMode="numeric" />
            </Field>
            <Field label="ИИН (физлицо РК)">
              <TextInput value={form.iin} onChange={(e) => setForm({ ...form, iin: e.target.value })} placeholder="12 цифр" maxLength={12} inputMode="numeric" />
            </Field>
            <Field label="Страна">
              <Select value={form.countryId} onChange={(e) => setForm({ ...form, countryId: e.target.value })}>
                <option value="">—</option>
                {countries.data?.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </Select>
            </Field>
            <Field label="Адрес" className="col-span-2">
              <TextInput value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} />
            </Field>
            <Field label="Телефон">
              <PhoneInput value={form.phone} onChange={(v) => setForm({ ...form, phone: v })} />
            </Field>
            <Field label="Email">
              <TextInput type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </Field>
            <Field label="Банк" className="col-span-2">
              <TextInput value={form.bankName} onChange={(e) => setForm({ ...form, bankName: e.target.value })} />
            </Field>
            <Field label="Расчётный счёт">
              <TextInput value={form.bankAccount} onChange={(e) => setForm({ ...form, bankAccount: e.target.value })} />
            </Field>
            <Field label="БИК">
              <TextInput value={form.bik} onChange={(e) => setForm({ ...form, bik: e.target.value })} />
            </Field>
            <Field label="Контактное лицо" className="col-span-2">
              <TextInput value={form.contactPerson} onChange={(e) => setForm({ ...form, contactPerson: e.target.value })} />
            </Field>
            <Field label="Заметки" className="col-span-2">
              <TextArea rows={3} value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} />
            </Field>
            <div className="col-span-2">
            </div>
          </div>
        )}
      </Modal>
    </>
  )
}
