'use client'

import { useEffect, useState } from 'react'
import { apiFetch } from '@/lib/api'

interface CustomerRow {
  id: string
  firstName: string
  lastName: string
  email: string
  phone: string | null
  flagged: boolean
  licenseValidationStatus: string
}

export default function CustomersPage() {
  const [rows, setRows] = useState<CustomerRow[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    apiFetch<CustomerRow[]>('/customers?pageSize=100')
      .then((result) => setRows(result ?? []))
      .catch((err) => setError(err.message))
  }, [])

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-xl font-semibold text-slate-900">Customers</h2>
        <p className="text-sm text-slate-500 mt-1">Company-scoped CRM with license validation and risk flags.</p>
      </div>
      <div className="card overflow-hidden">
        {error ? (
          <div className="p-8 text-sm text-red-600">{error}</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="bg-slate-50 border-b border-slate-200">
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Customer</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Contact</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">License</th>
                  <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Flags</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {rows.map((row) => (
                  <tr key={row.id}>
                    <td className="px-6 py-4 text-sm font-semibold text-slate-900">{row.firstName} {row.lastName}</td>
                    <td className="px-6 py-4">
                      <p className="text-sm text-slate-700">{row.email}</p>
                      <p className="text-xs text-slate-500">{row.phone ?? 'No phone'}</p>
                    </td>
                    <td className="px-6 py-4"><span className="badge-gray">{row.licenseValidationStatus}</span></td>
                    <td className="px-6 py-4">{row.flagged ? <span className="badge-red">Flagged</span> : <span className="badge-green">Clear</span>}</td>
                  </tr>
                ))}
                {rows.length === 0 && (
                  <tr>
                    <td colSpan={4} className="px-6 py-10 text-center text-sm text-slate-400">No customers yet.</td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  )
}
