import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { partners } from '@/api/client'
import type { Partner } from '@/types/api'
import { PageHeader } from '@/components/PageHeader'
import { Loading } from '@/components/Loading'
import { ErrorBox } from '@/components/ErrorBox'
import { DataTable, type Column } from '@/components/DataTable'

export function PartnersPage() {
  const [rows, setRows] = useState<Partner[]>([])
  const [error, setError] = useState<Error | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    partners
      .list()
      .then(setRows)
      .catch((e: unknown) => setError(e instanceof Error ? e : new Error(String(e))))
      .finally(() => setLoading(false))
  }, [])

  const columns: Column<Partner>[] = [
    {
      header: 'Code',
      key: 'code',
      render: (r) => (
        <Link to={`/partners/${r.id}/edit`} className="font-mono text-brand-600 hover:underline">{r.code}</Link>
      ),
    },
    { header: 'Name', key: 'name' },
    { header: 'Type', key: 'type' },
    { header: 'Email', key: 'email', render: (r) => r.email ?? '—' },
    { header: 'Phone', key: 'phone', render: (r) => r.phone ?? '—' },
    {
      header: 'Active',
      key: 'active',
      render: (r) => (r.active ? <span className="text-emerald-600">●</span> : <span className="text-slate-300">●</span>),
    },
  ]

  return (
    <div>
      <PageHeader
        title="Partners"
        subtitle="Customers, suppliers, and dual-role partners."
        actions={<Link to="/partners/new" className="btn-primary">+ New Partner</Link>}
      />
      {loading && <Loading />}
      {error && <ErrorBox error={error} />}
      {!loading && !error && <DataTable rows={rows} columns={columns} />}
    </div>
  )
}
