'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'

export default function NewClientPage() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    name: '',
    semaphoreKey: '',
    senderName: 'NFC-HUB',
  })

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError('')

    const res = await fetch('/api/clients', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(form),
    })

    if (res.ok) {
      router.push('/dashboard/clients')
    } else {
      const data = await res.json()
      setError(data.error || 'Failed to create client')
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/dashboard/clients">
          <Button variant="ghost" size="sm">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back
          </Button>
        </Link>
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Add Client</h1>
          <p className="text-gray-500">Register a new school or organization</p>
        </div>
      </div>

      <Card className="max-w-2xl">
        <CardHeader>
          <CardTitle>Client Details</CardTitle>
          <CardDescription>
            Each client gets a unique API key for their on-premise NFC attendance app.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">{error}</div>
            )}
            <div className="space-y-2">
              <Label htmlFor="name">Organization Name *</Label>
              <Input
                id="name"
                value={form.name}
                onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                placeholder="e.g. San Jose Elementary School"
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="semaphoreKey">Semaphore API Key</Label>
              <Input
                id="semaphoreKey"
                value={form.semaphoreKey}
                onChange={e => setForm(f => ({ ...f, semaphoreKey: e.target.value }))}
                placeholder="Your Semaphore API key"
              />
              <p className="text-xs text-gray-500">You can add this later in client settings.</p>
            </div>
            <div className="space-y-2">
              <Label htmlFor="senderName">SMS Sender Name</Label>
              <Input
                id="senderName"
                value={form.senderName}
                onChange={e => setForm(f => ({ ...f, senderName: e.target.value }))}
                placeholder="NFC-HUB"
                maxLength={11}
              />
              <p className="text-xs text-gray-500">Max 11 characters. Must be registered with Semaphore.</p>
            </div>
            <div className="flex gap-3 pt-2">
              <Button type="submit" disabled={loading}>
                {loading ? 'Creating...' : 'Create Client'}
              </Button>
              <Link href="/dashboard/clients">
                <Button type="button" variant="outline">Cancel</Button>
              </Link>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
