'use client'

import { useState, useEffect, use } from 'react'
import { Loader2, FileText, Download, Printer, MapPin, Send, CheckCircle, XCircle } from 'lucide-react'

interface RapportViewData {
  id: string
  reportNumber: string
  data: any
  generatedAt: string
  project: { title: string; location: string | null }
  tenant: { name: string }
  createdBy: { name: string } | null
}

export default function RapportViewerPage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = use(params)
  const [rapport, setRapport] = useState<RapportViewData | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const [showEmailInput, setShowEmailInput] = useState(false)
  const [emailTo, setEmailTo] = useState('')
  const [emailSending, setEmailSending] = useState(false)
  const [emailStatus, setEmailStatus] = useState<'sent' | 'error' | null>(null)

  useEffect(() => {
    async function load() {
      try {
        const res = await fetch(`/api/rapports/${token}`)
        if (res.ok) {
          setRapport(await res.json())
        } else {
          setError('Rapport nicht gefunden oder Link ungültig.')
        }
      } catch {
        setError('Fehler beim Laden des Rapports.')
      } finally {
        setIsLoading(false)
      }
    }
    load()
  }, [token])

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <Loader2 className="w-8 h-8 animate-spin text-red-500 mx-auto mb-2" />
          <p className="text-sm text-gray-500">Rapport wird geladen...</p>
        </div>
      </div>
    )
  }

  if (error || !rapport) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center max-w-md">
          <FileText className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h1 className="text-lg font-bold text-gray-900 mb-2">Rapport nicht verfügbar</h1>
          <p className="text-sm text-gray-500">{error}</p>
        </div>
      </div>
    )
  }

  const d = rapport.data
  const pdfUrl = `/api/rapports/${token}/pdf`

  return (
    <div className="min-h-screen bg-gray-100 py-8">
      {/* Action bar */}
      <div className="max-w-[210mm] mx-auto mb-4 flex justify-between items-center px-4">
        <div className="flex items-center gap-2">
          <img src="/logo.svg" alt="Lageplan" className="w-5 h-5 object-contain" />
          <span className="font-semibold text-sm">Lageplan — Einsatzrapport</span>
        </div>
        <div className="flex gap-2">
          <a
            href={pdfUrl}
            target="_blank"
            className="inline-flex items-center gap-1.5 px-4 py-2 bg-white border rounded-md text-sm font-medium hover:bg-gray-50 transition-colors"
          >
            <Download className="w-4 h-4" />
            PDF herunterladen
          </a>
          <button
            onClick={() => { setShowEmailInput(!showEmailInput); setEmailStatus(null) }}
            className="inline-flex items-center gap-1.5 px-4 py-2 bg-white border rounded-md text-sm font-medium hover:bg-gray-50 transition-colors"
          >
            <Send className="w-4 h-4" />
            Per E-Mail
          </button>
          <button
            onClick={() => window.print()}
            className="inline-flex items-center gap-1.5 px-4 py-2 bg-gray-900 text-white rounded-md text-sm font-medium hover:bg-gray-800 transition-colors"
          >
            <Printer className="w-4 h-4" />
            Drucken
          </button>
        </div>
      </div>

      {/* Email send bar */}
      {showEmailInput && (
        <div className="max-w-[210mm] mx-auto mb-4 px-4 print:hidden">
          <div className="flex items-center gap-2 bg-white border rounded-lg p-3">
            <input
              type="email"
              placeholder="E-Mail-Adresse..."
              value={emailTo}
              onChange={e => { setEmailTo(e.target.value); setEmailStatus(null) }}
              className="flex-1 text-sm border rounded px-3 py-1.5 outline-none focus:ring-2 focus:ring-gray-300"
              onKeyDown={e => { if (e.key === 'Enter') document.getElementById('send-email-btn')?.click() }}
            />
            <button
              id="send-email-btn"
              disabled={emailSending || !emailTo.includes('@')}
              onClick={async () => {
                setEmailSending(true)
                setEmailStatus(null)
                try {
                  const res = await fetch(`/api/rapports/${token}/send`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ email: emailTo }),
                  })
                  setEmailStatus(res.ok ? 'sent' : 'error')
                  if (res.ok) setEmailTo('')
                } catch { setEmailStatus('error') } finally { setEmailSending(false) }
              }}
              className="inline-flex items-center gap-1.5 px-4 py-1.5 bg-gray-900 text-white rounded text-sm font-medium hover:bg-gray-800 disabled:opacity-50 transition-colors"
            >
              {emailSending ? <Loader2 className="w-4 h-4 animate-spin" /> : <Send className="w-4 h-4" />}
              Senden
            </button>
            {emailStatus === 'sent' && <CheckCircle className="w-5 h-5 text-green-500" />}
            {emailStatus === 'error' && <XCircle className="w-5 h-5 text-red-500" />}
          </div>
        </div>
      )}

      {/* Rapport card */}
      <div className="max-w-[210mm] mx-auto bg-white shadow-lg rounded-lg p-8 print:shadow-none print:rounded-none print:p-6">
        {/* Header */}
        <div className="flex justify-between items-start pb-3 border-b-[3px] border-gray-900 mb-1">
          <div className="flex items-center gap-3">
            {d.logoUrl && (
              <img src={d.logoUrl} alt="Logo" className="w-10 h-10 object-contain" />
            )}
            <div>
              <h1 className="text-2xl font-bold tracking-tight">Einsatzrapport</h1>
              <p className="text-xs text-gray-500 mt-0.5 font-medium">{d.organisation} · {d.abteilung}</p>
            </div>
          </div>
          <div className="text-right">
            <div className="text-xl font-bold text-red-700 font-mono">{rapport.reportNumber}</div>
            <div className="text-xs text-gray-500">{d.datum} · {d.uhrzeit}</div>
          </div>
        </div>
        <div className="h-[3px] bg-gradient-to-r from-red-700 from-30% to-gray-200 to-30% mb-4" />

        {/* 1. Einsatzdaten */}
        <Section num="1" title="Einsatzdaten">
          <div className="grid grid-cols-4 border rounded">
            <Field label="Einsatz-Nr." value={d.einsatzNr} mono />
            <Field label="Datum" value={d.datum} />
            <Field label="Alarmzeit" value={d.alarmzeit} mono />
            <Field label="Priorität" value={d.prioritaet} last />
            <Field label="Einsatzort / Adresse" value={d.einsatzort} span={2} />
            <Field label="Objekt / Gebäude" value={d.objekt} span={2} last />
            <Field label="Alarmierungsart" value={d.alarmierungsart} span={2} />
            <Field label="Stichwort / Meldebild" value={d.stichwort} span={2} last />
          </div>
        </Section>

        {/* 2. Zeitverlauf */}
        <Section num="2" title="Zeitverlauf">
          <div className="grid grid-cols-2 border rounded">
            <Field label="Alarmierung" value={d.zeitAlarm} mono highlight />
            <Field label="Eintreffen" value={d.zeitEintreffen} mono highlight last />
          </div>
        </Section>

        {/* 3. Lagebild */}
        <Section num="3" title="Lagebild">
          <div className="grid grid-cols-1 border rounded">
            <Field label="Lage bei Eintreffen" value={d.lageEintreffen} span={1} />
            <div className={`p-2 border-b border-r-0 border-gray-100 col-span-1`}>
              <div className="text-[6.5pt] font-semibold uppercase tracking-wider text-gray-400 mb-0.5">Getroffene Massnahmen</div>
              {Array.isArray(d.massnahmen) ? (
                <ul className="text-[9pt] font-medium list-none space-y-0.5">
                  {d.massnahmen.map((m: string, i: number) => (
                    <li key={i}>• {m}</li>
                  ))}
                </ul>
              ) : (
                <div className="text-[9pt] font-medium min-h-[14px] whitespace-pre-line">{d.massnahmen || '—'}</div>
              )}
            </div>
          </div>
        </Section>

        {/* 4. Lageplan-Karte */}
        {d.mapScreenshot && (
          <Section num="4" title="Lageplan / Skizze">
            <div className="border rounded overflow-hidden">
              <img src={d.mapScreenshot} alt="Lageplan" className="w-full h-auto max-h-[80mm] object-contain" />
            </div>
          </Section>
        )}

        {/* 5. SOMA Checkliste */}
        {Array.isArray(d.somaItems) && d.somaItems.length > 0 && (
          <Section num="5" title="SOMA Checkliste">
            <div className="border rounded">
              <div className="grid grid-cols-[24px_24px_1fr_60px] gap-0 text-[7pt] font-semibold uppercase tracking-wider bg-gray-900 text-white p-1.5">
                <span className="text-center">Best.</span>
                <span className="text-center">OK</span>
                <span>Punkt</span>
                <span className="text-right">Zeit</span>
              </div>
              {d.somaItems.map((s: any, i: number) => (
                <div key={i} className={`grid grid-cols-[24px_24px_1fr_60px] gap-0 p-1.5 border-b border-gray-100 text-[9pt] ${i % 2 === 1 ? 'bg-gray-50' : ''}`}>
                  <span className="text-center font-bold">{s.confirmed ? '✓' : '—'}</span>
                  <span className="text-center font-bold">{s.ok ? '✓' : '—'}</span>
                  <span className="font-medium">{s.label}</span>
                  <span className="text-right text-[8pt] text-gray-500 font-mono">{s.confirmedAt || ''}</span>
                </div>
              ))}
            </div>
          </Section>
        )}

        {/* 6. Pendenzen */}
        {Array.isArray(d.pendenzenItems) && d.pendenzenItems.length > 0 && (
          <Section num="6" title="Pendenzen">
            <table className="w-full border-collapse border rounded text-xs">
              <thead>
                <tr className="bg-gray-900 text-white">
                  <th className="p-1.5 text-center font-semibold uppercase tracking-wider text-[7pt] w-8">✓</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Aufgabe</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt] w-24">Wer</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt] w-32">Wann / Wie</th>
                  <th className="p-1.5 text-right font-semibold uppercase tracking-wider text-[7pt] w-16">Erledigt</th>
                </tr>
              </thead>
              <tbody>
                {d.pendenzenItems.map((p: any, i: number) => (
                  <tr key={i} className={`${i % 2 === 1 ? 'bg-gray-50' : ''} ${p.done ? 'text-gray-400' : ''}`}>
                    <td className="p-1.5 border-b border-gray-100 text-center font-bold">{p.done ? '✓' : '○'}</td>
                    <td className={`p-1.5 border-b border-gray-100 ${p.done ? 'line-through' : ''}`}>{p.what}</td>
                    <td className="p-1.5 border-b border-gray-100 text-gray-500">{p.who || '—'}</td>
                    <td className="p-1.5 border-b border-gray-100 text-gray-500">{p.whenHow || '—'}</td>
                    <td className="p-1.5 border-b border-gray-100 text-right font-mono text-[8pt]">{p.doneAt || ''}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Section>
        )}

        {/* 7. Eingesetzte Mittel */}
        {d.fahrzeuge?.length > 0 && (
          <Section num="7" title="Eingesetzte Mittel">
            <table className="w-full border-collapse border rounded text-xs">
              <thead>
                <tr className="bg-gray-900 text-white">
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Fahrzeug</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Pers.</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Ausrücken</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Eintreffen</th>
                  <th className="p-1.5 text-left font-semibold uppercase tracking-wider text-[7pt]">Auftrag</th>
                </tr>
              </thead>
              <tbody>
                {d.fahrzeuge.map((fz: any, i: number) => (
                  <tr key={i} className={i % 2 === 1 ? 'bg-gray-50' : ''}>
                    <td className="p-1.5 border-b border-gray-100">{fz.name}</td>
                    <td className="p-1.5 border-b border-gray-100">{fz.pers}</td>
                    <td className="p-1.5 border-b border-gray-100">{fz.ausruecken}</td>
                    <td className="p-1.5 border-b border-gray-100">{fz.eintreffen}</td>
                    <td className="p-1.5 border-b border-gray-100">{fz.auftrag}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Section>
        )}

        {/* 8. Bemerkungen */}
        <Section num="8" title="Bemerkungen / Besondere Vorkommnisse">
          <div className="border rounded p-3 min-h-[50px] text-sm">{d.bemerkungen || '—'}</div>
        </Section>

        {/* Unterschriften */}
        <div className="flex gap-12 mt-6 mb-6">
          <div className="flex-1">
            <div className="border-b border-gray-900 h-8 mb-1" />
            <p className="text-[7pt] text-gray-500">Einsatzleiter/in · {d.einsatzleiter}</p>
          </div>
          <div className="flex-1">
            <div className="border-b border-gray-900 h-8 mb-1" />
            <p className="text-[7pt] text-gray-500">Rapport erstellt durch · {d.rapporteur}</p>
          </div>
          <div className="flex-1">
            <div className="border-b border-gray-900 h-8 mb-1" />
            <p className="text-[7pt] text-gray-500">Datum / Visum Kdt</p>
          </div>
        </div>

        {/* Footer with QR code */}
        <div className="flex justify-between items-end pt-3 border-t border-gray-200 text-[7pt] text-gray-400">
          <div>
            Erstellt: {d.datum} {d.uhrzeit} · {d.organisation}<br />
            Rapport: {rapport.reportNumber}
          </div>
          {d.qrCodeUrl && (
            <div className="flex flex-col items-center">
              <img src={d.qrCodeUrl} alt="QR-Code" className="w-16 h-16" />
              <span className="text-[5pt] text-gray-400 mt-0.5">Online-Rapport</span>
            </div>
          )}
          <div className="text-right">
            app.lageplan.ch
          </div>
        </div>
      </div>
    </div>
  )
}

function Section({ num, title, children }: { num: string; title: string; children: React.ReactNode }) {
  return (
    <div className="mb-4">
      <div className="flex items-center gap-2 mb-2">
        <span className="w-5 h-5 bg-gray-900 text-white rounded text-[8pt] font-bold flex items-center justify-center">{num}</span>
        <span className="text-[9pt] font-bold uppercase tracking-wider">{title}</span>
        <div className="flex-1 h-px bg-gray-200 ml-2" />
      </div>
      {children}
    </div>
  )
}

function Field({ label, value, mono, highlight, span, last }: {
  label: string; value: string; mono?: boolean; highlight?: boolean; span?: number; last?: boolean
}) {
  return (
    <div className={`p-2 border-b border-r border-gray-100 ${highlight ? 'bg-gray-50' : ''} ${span === 2 ? 'col-span-2' : ''} ${last ? 'border-r-0' : ''}`}>
      <div className="text-[6.5pt] font-semibold uppercase tracking-wider text-gray-400 mb-0.5">{label}</div>
      <div className={`text-[9pt] font-medium min-h-[14px] ${mono ? 'font-mono text-[8.5pt]' : ''}`}>{value || '—'}</div>
    </div>
  )
}
