'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { trpc } from '@/lib/trpc-client'
import { getTrpcErrorMessage } from '@/lib/trpc-error'
import Link from 'next/link'
import dynamic from 'next/dynamic'
import { AIGenerator } from '@/components/ai-generator'

const MDEditor = dynamic(() => import('@uiw/react-md-editor'), { ssr: false })

const KATEGORIEN = [
  { value: 'Wichtig', label: 'Wichtig' },
  { value: 'Pruefung', label: 'Prüfung' },
  { value: 'Foerderung', label: 'Förderung' },
  { value: 'Veranstaltung', label: 'Veranstaltung' },
  { value: 'Allgemein', label: 'Allgemein' },
]

export default function NewsNeuPage() {
  const router = useRouter()
  const [title, setTitle] = useState('')
  const DEFAULT_BODY = '## Inhalt\n\nHier können Sie Ihren Beitrag verfassen.'
  const [body, setBody] = useState(DEFAULT_BODY)
  const [kategorie, setKategorie] = useState('Allgemein')
  const [uploading, setUploading] = useState(false)
  const [attachments, setAttachments] = useState<
    Array<{ name: string; storagePath: string; sizeBytes: number; url: string }>
  >([])

  const createMutation = trpc.news.create.useMutation({
    onSuccess: () => router.push('/dashboard/news'),
  })

  function handleSubmit(publishNow: boolean) {
    if (!title.trim() || !body.trim()) return
    createMutation.mutate({
      title,
      body,
      kategorie: kategorie as never,
      publishedAt: publishNow ? new Date().toISOString() : null,
      attachments: attachments.map((a) => ({
        name: a.name,
        storagePath: a.storagePath,
        sizeBytes: a.sizeBytes,
        mimeType: 'application/pdf', // fallback/default; the API handles it
      })),
    })
  }

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return
    setUploading(true)
    const formData = new FormData()
    formData.append('file', file)
    try {
      const res = await fetch('/api/upload', { method: 'POST', body: formData })
      const data = await res.json()
      setAttachments((prev) => [...prev, data])
    } catch {
      alert('Upload fehlgeschlagen')
    } finally {
      setUploading(false)
    }
  }

  return (
    <div className="max-w-6xl space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/dashboard/news" className="text-gray-400 hover:text-gray-600">
          ← Zurück
        </Link>
        <h1 className="text-2xl font-bold text-gray-900">Beitrag erstellen</h1>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-start">
        <div className="lg:col-span-2 bg-white rounded-xl border shadow-sm p-6 space-y-4">
          <div className="grid grid-cols-3 gap-4">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-1">Titel *</label>
              <input
                required
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="Aussagekräftiger Titel..."
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Kategorie</label>
              <select
                value={kategorie}
                onChange={(e) => setKategorie(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"
              >
                {KATEGORIEN.map((k) => (
                  <option key={k.value} value={k.value}>{k.label}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Inhalt *</label>
            <div data-color-mode="light">
              <MDEditor
                value={body}
                onChange={(v) => setBody(v ?? '')}
                height={400}
                preview="live"
              />
            </div>
          </div>

          {/* Attachments */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Anhänge (PDF)</label>
            <label className="cursor-pointer inline-flex items-center gap-2 px-4 py-2 border border-dashed border-gray-300 rounded-lg text-sm text-gray-500 hover:border-brand-500 hover:text-brand-500 transition-colors">
              {uploading ? '⏳ Hochladen...' : '📎 Datei anhängen'}
              <input
                type="file"
                accept=".pdf,image/*"
                onChange={handleFileUpload}
                disabled={uploading}
                className="hidden"
              />
            </label>
            {attachments.length > 0 && (
              <ul className="mt-2 space-y-1">
                {attachments.map((a, i) => (
                  <li key={i} className="flex items-center gap-2 text-sm text-gray-600">
                    <span>📄</span>
                    <span>{a.name}</span>
                    <span className="text-gray-400">({Math.round(a.sizeBytes / 1024)} KB)</span>
                  </li>
                ))}
              </ul>
            )}
          </div>

          {createMutation.error && (
            <p className="text-sm text-red-600 bg-red-50 px-4 py-2 rounded-lg">
              {getTrpcErrorMessage(createMutation.error)}
            </p>
          )}

          <div className="flex gap-3 pt-2 border-t">
            <button
              onClick={() => handleSubmit(true)}
              disabled={createMutation.isPending}
              className="bg-brand-500 text-white px-6 py-2 rounded-lg text-sm font-medium hover:bg-brand-600 disabled:opacity-60 transition-colors"
            >
              Jetzt publizieren
            </button>
            <button
              onClick={() => handleSubmit(false)}
              disabled={createMutation.isPending}
              className="px-6 py-2 rounded-lg text-sm font-medium text-gray-700 border hover:bg-gray-50 transition-colors"
            >
              Als Entwurf speichern
            </button>
          </div>
        </div>

        <div className="lg:col-span-1 sticky top-6">
          <AIGenerator
            type="news"
            onApply={(generated) => {
              // Replace placeholder if untouched, otherwise append
              setBody(body === DEFAULT_BODY ? generated : body + '\n\n' + generated)
            }}
          />
        </div>
      </div>
    </div>
  )
}
