import { useState, useEffect } from 'react'
import { adminApi } from '@/api/admin'
import type { SurveyInviteResponse } from '@/api/admin'
import { PageHeader } from '@/components/admin'
import { Copy, Check, Mail, Link2, Loader2, Send } from 'lucide-react'
import { cn } from '@/lib/utils'

export default function SurveyInvitesPage() {
  const [invites, setInvites] = useState<SurveyInviteResponse[]>([])
  const [loading, setLoading] = useState(true)
  const [creating, setCreating] = useState(false)
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [lastCreated, setLastCreated] = useState<SurveyInviteResponse | null>(null)
  const [copied, setCopied] = useState(false)
  const [error, setError] = useState('')

  const fetchInvites = async () => {
    try {
      const data = await adminApi.listSurveyInvites()
      setInvites(data)
    } catch {
      setError('Failed to load invites')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { fetchInvites() }, [])

  const handleCreate = async (sendEmail: boolean) => {
    if (!name.trim()) return
    if (sendEmail && !email.trim()) return
    setCreating(true)
    setError('')
    try {
      const invite = await adminApi.createSurveyInvite({
        recipient_name: name.trim(),
        recipient_email: email.trim() || undefined,
        send_email: sendEmail,
      })
      setLastCreated(invite)
      setName('')
      setEmail('')
      setInvites(prev => [invite, ...prev])
    } catch {
      setError('Failed to create invite')
    } finally {
      setCreating(false)
    }
  }

  const handleCopy = async (url: string) => {
    await navigator.clipboard.writeText(url)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const formatDate = (dateStr: string) => {
    return new Date(dateStr).toLocaleDateString('en-US', {
      month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit',
    })
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Survey Invites"
        description="Create personalized survey links and track responses"
      />

      {/* Create Invite Section */}
      <div className="card-flat p-6">
        <h3 className="font-heading text-sm font-semibold text-foreground mb-4">Create Invite</h3>
        <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
          <div className="flex-1">
            <label className="font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground mb-1.5 block">
              Recipient Name
            </label>
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="John Smith"
              className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary/30 focus:outline-hidden"
            />
          </div>
          <div className="flex-1">
            <label className="font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground mb-1.5 block">
              Email (optional)
            </label>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="john@example.com"
              className="w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:border-primary/30 focus:outline-hidden"
            />
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => handleCreate(false)}
              disabled={creating || !name.trim()}
              className="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:brightness-110 active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Link2 className="h-4 w-4" />}
              Generate Link
            </button>
            <button
              onClick={() => handleCreate(true)}
              disabled={creating || !name.trim() || !email.trim()}
              className="inline-flex items-center gap-2 rounded-lg bg-input border border-border px-4 py-2 text-sm font-medium text-foreground hover:border-border-hover active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed transition-all"
            >
              {creating ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
              Send Email
            </button>
          </div>
        </div>

        {error && (
          <p className="mt-3 text-sm text-rose-500">{error}</p>
        )}

        {lastCreated && (
          <div className="mt-4 rounded-lg border border-primary/[0.15] bg-primary/[0.04] p-4">
            <div className="flex items-center justify-between gap-3">
              <div className="min-w-0 flex-1">
                <p className="text-xs text-muted-foreground mb-1">
                  {lastCreated.email_sent ? 'Email sent to ' + lastCreated.recipient_email + '! Link:' : 'Share this link with ' + lastCreated.recipient_name + ':'}
                </p>
                <p className="truncate text-sm font-mono text-foreground">{lastCreated.survey_url}</p>
              </div>
              <button
                onClick={() => handleCopy(lastCreated.survey_url)}
                className="shrink-0 rounded-lg p-2 text-muted-foreground hover:bg-border hover:text-foreground transition-colors"
              >
                {copied ? <Check className="h-4 w-4 text-emerald-400" /> : <Copy className="h-4 w-4" />}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Invites Table */}
      <div className="card-flat overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-border">
                <th className="px-4 py-3 text-left font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Name</th>
                <th className="px-4 py-3 text-left font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Email</th>
                <th className="px-4 py-3 text-left font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Status</th>
                <th className="px-4 py-3 text-center font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Sent</th>
                <th className="px-4 py-3 text-left font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Created</th>
                <th className="px-4 py-3 text-left font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Completed</th>
                <th className="px-4 py-3 text-center font-sans text-xs text-[0.625rem] uppercase tracking-widest text-muted-foreground">Link</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-sm text-muted-foreground">Loading...</td></tr>
              ) : invites.length === 0 ? (
                <tr><td colSpan={7} className="px-4 py-8 text-center text-sm text-muted-foreground">No invites yet</td></tr>
              ) : (
                invites.map(invite => (
                  <tr key={invite.id} className="border-b border-border/50 hover:bg-card transition-colors">
                    <td className="px-4 py-3 text-sm text-foreground">{invite.recipient_name}</td>
                    <td className="px-4 py-3 text-sm text-muted-foreground">{invite.recipient_email || '—'}</td>
                    <td className="px-4 py-3">
                      <span className={cn(
                        'inline-flex items-center rounded-full px-2 py-0.5 font-sans text-xs text-[0.625rem] uppercase tracking-wider',
                        invite.status === 'completed'
                          ? 'bg-emerald-400/10 text-emerald-400'
                          : 'bg-amber-400/10 text-amber-400'
                      )}>
                        {invite.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-center">
                      {invite.email_sent ? (
                        <Mail className="mx-auto h-4 w-4 text-muted-foreground" />
                      ) : (
                        <span className="text-muted-foreground/50">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3 font-sans text-xs text-xs text-muted-foreground">{formatDate(invite.created_at)}</td>
                    <td className="px-4 py-3 font-sans text-xs text-xs text-muted-foreground">{invite.completed_at ? formatDate(invite.completed_at) : '—'}</td>
                    <td className="px-4 py-3 text-center">
                      <button
                        onClick={() => handleCopy(invite.survey_url)}
                        className="rounded-lg p-1.5 text-muted-foreground hover:bg-border hover:text-foreground transition-colors"
                        title="Copy survey link"
                      >
                        <Copy className="h-3.5 w-3.5" />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
