'use client'
import { useState, useEffect } from 'react'
import { useParams, 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 { Badge } from '@/components/ui/badge'
import Link from 'next/link'
import { ArrowLeft, RefreshCw, Copy, Check } from 'lucide-react'

export default function ClientSettingsPage() {
  const params = useParams()
  const router = useRouter()
  const [client, setClient] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [copied, setCopied] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [form, setForm] = useState({ name: '', semaphoreKey: '', senderName: '', isActive: true })

  useEffect(() => {
    fetch(`/api/clients/${params.id}`)
      .then(r => r.json())
      .then(data => {
        setClient(data)
        setForm({
          name: data.name,
          semaphoreKey: data.semaphoreKey || '',
          senderName: data.senderName || 'NFC-HUB',
          isActive: data.isActive,
        })
        setLoading(false)
      })
  }, [params.id])

  async function handleSave(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true)
    setError('')
    setSuccess('')

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

    if (res.ok) {
      setSuccess('Settings saved successfully')
      const updated = await res.json()
      setClient((prev: any) => ({ ...prev, ...updated }))
    } else {
      const data = await res.json()
      setError(data.error || 'Save failed')
    }
    setSaving(false)
  }

  async function copyApiKey() {
    await navigator.clipboard.writeText(client.apiKey)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  if (loading) return <div className="text-gray-500">Loading...</div>
  if (!client) return <div className="text-red-500">Client not found</div>

  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">{client.name}</h1>
          <p className="text-gray-500">Client settings and API configuration</p>
        </div>
      </div>

      {/* API Key Card */}
      <Card>
        <CardHeader>
          <CardTitle>API Key</CardTitle>
          <CardDescription>Use this key in the X-API-Key header for SMS submissions.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2">
            <code className="flex-1 bg-gray-100 px-4 py-2 rounded-md text-sm font-mono">{client.apiKey}</code>
            <Button variant="outline" size="sm" onClick={copyApiKey}>
              {copied ? <Check className="h-4 w-4 text-green-600" /> : <Copy className="h-4 w-4" />}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Credit Balance */}
      {client.semaphoreKey && (
        <Card>
          <CardHeader>
            <CardTitle>Semaphore Credits</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-3xl font-bold text-green-600">
              {client.balance !== null ? client.balance.toLocaleString() : 'N/A'}
            </div>
            <p className="text-sm text-gray-500 mt-1">Available SMS credits</p>
          </CardContent>
        </Card>
      )}

      {/* Settings Form */}
      <Card className="max-w-2xl">
        <CardHeader>
          <CardTitle>Settings</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSave} 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>}
            {success && <div className="bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-md text-sm">{success}</div>}
            <div className="space-y-2">
              <Label>Organization Name</Label>
              <Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} required />
            </div>
            <div className="space-y-2">
              <Label>Semaphore API Key</Label>
              <Input
                value={form.semaphoreKey}
                onChange={e => setForm(f => ({ ...f, semaphoreKey: e.target.value }))}
                placeholder="Enter Semaphore API key"
                type="password"
              />
            </div>
            <div className="space-y-2">
              <Label>SMS Sender Name</Label>
              <Input
                value={form.senderName}
                onChange={e => setForm(f => ({ ...f, senderName: e.target.value }))}
                maxLength={11}
              />
            </div>
            <div className="flex items-center gap-3">
              <input
                type="checkbox"
                id="isActive"
                checked={form.isActive}
                onChange={e => setForm(f => ({ ...f, isActive: e.target.checked }))}
                className="h-4 w-4"
              />
              <Label htmlFor="isActive">Client is active</Label>
            </div>
            <Button type="submit" disabled={saving}>
              {saving ? 'Saving...' : 'Save Settings'}
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  )
}
