import React from 'react'
import { Document, Page, Text, View, StyleSheet, Font, Image } from '@react-pdf/renderer'

// Register default font (Helvetica is built-in)
const styles = StyleSheet.create({
  page: {
    padding: '12mm 15mm 32mm',
    fontFamily: 'Helvetica',
    fontSize: 10,
    lineHeight: 1.4,
    color: '#1a1a1a',
  },
  // Header
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    paddingBottom: 8,
    borderBottomWidth: 2.5,
    borderBottomColor: '#1a1a1a',
    marginBottom: 4,
  },
  headerLeft: { flexDirection: 'row', alignItems: 'center', gap: 12 },
  headerTitle: { fontSize: 18, fontFamily: 'Helvetica-Bold', letterSpacing: -0.5 },
  headerSubtitle: { fontSize: 8, color: '#555', marginTop: 2, fontFamily: 'Helvetica-Bold' },
  headerRight: { textAlign: 'right' },
  eventId: { fontSize: 16, fontFamily: 'Helvetica-Bold', color: '#c0392b' },
  eventDate: { fontSize: 8, color: '#555', marginTop: 2 },
  headerStripe: { height: 3, marginBottom: 10, backgroundColor: '#c0392b' },
  // Sections
  section: { marginBottom: 10 },
  sectionHeader: { flexDirection: 'row', alignItems: 'center', gap: 6, marginBottom: 5 },
  sectionNumber: {
    width: 18, height: 18, backgroundColor: '#1a1a1a', borderRadius: 3,
    color: '#fff', fontSize: 8, fontFamily: 'Helvetica-Bold',
    textAlign: 'center', paddingTop: 3,
  },
  sectionTitle: { fontSize: 9, fontFamily: 'Helvetica-Bold', textTransform: 'uppercase', letterSpacing: 0.8 },
  sectionLine: { flex: 1, height: 1, backgroundColor: '#d0d0d0', marginLeft: 6 },
  // Field grid
  fieldGrid: { borderWidth: 1, borderColor: '#d0d0d0', borderRadius: 4 },
  fieldRow: { flexDirection: 'row' },
  field: { padding: '5 8', borderBottomWidth: 1, borderBottomColor: '#e8e8e8', borderRightWidth: 1, borderRightColor: '#e8e8e8', minHeight: 32 },
  fieldLabel: { fontSize: 6.5, fontFamily: 'Helvetica-Bold', textTransform: 'uppercase', letterSpacing: 0.5, color: '#888', marginBottom: 1 },
  fieldValue: { fontSize: 9, fontFamily: 'Helvetica-Bold', color: '#1a1a1a', minHeight: 14 },
  fieldValueMono: { fontSize: 8.5, fontFamily: 'Courier', color: '#1a1a1a', minHeight: 14 },
  fieldHighlight: { backgroundColor: '#f5f5f5' },
  // Resource table
  tableHeader: { flexDirection: 'row', backgroundColor: '#1a1a1a' },
  tableHeaderCell: { padding: '4 8', fontSize: 7, fontFamily: 'Helvetica-Bold', textTransform: 'uppercase', letterSpacing: 0.5, color: '#fff' },
  tableRow: { flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#e8e8e8' },
  tableRowEven: { backgroundColor: '#f5f5f5' },
  tableCell: { padding: '4 8', fontSize: 8.5 },
  // Notes
  notesBox: { borderWidth: 1, borderColor: '#d0d0d0', borderRadius: 4, padding: 8, minHeight: 50 },
  notesText: { fontSize: 9, color: '#1a1a1a' },
  // Signatures
  signatureBlock: { flexDirection: 'row', gap: 30, marginTop: 8, marginBottom: 20 },
  signatureField: { flex: 1 },
  signatureLine: { borderBottomWidth: 1, borderBottomColor: '#1a1a1a', height: 25, marginBottom: 3 },
  signatureLabel: { fontSize: 7, color: '#888' },
  // Footer
  footer: {
    position: 'absolute', bottom: '10mm', left: '15mm', right: '15mm',
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end',
    paddingTop: 6, borderTopWidth: 1, borderTopColor: '#d0d0d0', fontSize: 7, color: '#888',
  },
  // Map placeholder
  mapContainer: {
    borderWidth: 1, borderColor: '#d0d0d0', borderRadius: 4,
    height: '80mm', backgroundColor: '#f5f5f5',
    justifyContent: 'center', alignItems: 'center',
  },
  mapPlaceholder: { fontSize: 9, color: '#888', textAlign: 'center' },
  // Priority badges
  priorityHigh: { backgroundColor: '#fde8e8', color: '#991b1b', padding: '2 8', borderRadius: 3, fontSize: 7.5, fontFamily: 'Helvetica-Bold' },
  priorityMedium: { backgroundColor: '#fef3cd', color: '#856404', padding: '2 8', borderRadius: 3, fontSize: 7.5, fontFamily: 'Helvetica-Bold' },
  priorityLow: { backgroundColor: '#d4edda', color: '#155724', padding: '2 8', borderRadius: 3, fontSize: 7.5, fontFamily: 'Helvetica-Bold' },
})

export interface RapportData {
  reportNumber: string
  organisation: string
  abteilung: string
  datum: string
  uhrzeit: string
  einsatzNr: string
  alarmzeit: string
  prioritaet: string
  einsatzort: string
  koordinaten: string
  objekt: string
  alarmierungsart: string
  stichwort: string
  zeitAlarm: string
  zeitAusruecken: string
  zeitEintreffen: string
  zeitBereit: string
  zeitKontrolle: string
  zeitAus: string
  zeitEinruecken: string
  zeitEnde: string
  lageEintreffen: string
  massnahmen: string | string[]
  fahrzeuge: { name: string; pers: string; ausruecken: string; eintreffen: string; auftrag: string }[]
  bemerkungen: string
  einsatzleiter: string
  rapporteur: string
  qrCodeUrl?: string
  mapScreenshot?: string
  logoUrl?: string
}

function PriorityBadge({ priority }: { priority: string }) {
  const p = priority.toLowerCase()
  const style = p === 'hoch' || p === 'high' ? styles.priorityHigh
    : p === 'mittel' || p === 'medium' ? styles.priorityMedium
    : styles.priorityLow
  return <Text style={style}>{priority.toUpperCase()}</Text>
}

function FieldCell({ label, value, mono, highlight, width }: { label: string; value: string; mono?: boolean; highlight?: boolean; width: string }) {
  return (
    <View style={[styles.field, highlight ? styles.fieldHighlight : {}, { width }]}>
      <Text style={styles.fieldLabel}>{label}</Text>
      <Text style={mono ? styles.fieldValueMono : styles.fieldValue}>{value || '—'}</Text>
    </View>
  )
}

export function RapportDocument({ data }: { data: RapportData }) {
  return (
    <Document>
      <Page size="A4" style={styles.page}>
        {/* Header */}
        <View style={styles.header}>
          <View style={styles.headerLeft}>
            {data.logoUrl ? (
              <Image src={data.logoUrl} style={{ width: 40, height: 40, marginRight: 10, objectFit: 'contain' }} />
            ) : null}
            <View>
              <Text style={styles.headerTitle}>Einsatzrapport</Text>
              <Text style={styles.headerSubtitle}>{data.organisation} · {data.abteilung}</Text>
            </View>
          </View>
          <View style={styles.headerRight}>
            <Text style={styles.eventId}>{data.reportNumber}</Text>
            <Text style={styles.eventDate}>{data.datum} · {data.uhrzeit}</Text>
          </View>
        </View>
        <View style={styles.headerStripe} />

        {/* 1. Einsatzdaten */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>1</Text>
            <Text style={styles.sectionTitle}>Einsatzdaten</Text>
            <View style={styles.sectionLine} />
          </View>
          <View style={styles.fieldGrid}>
            <View style={styles.fieldRow}>
              <FieldCell label="Einsatz-Nr." value={data.einsatzNr} mono width="25%" />
              <FieldCell label="Datum" value={data.datum} width="25%" />
              <FieldCell label="Alarmzeit" value={data.alarmzeit} mono width="25%" />
              <FieldCell label="Priorität" value={data.prioritaet} width="25%" />
            </View>
            <View style={styles.fieldRow}>
              <FieldCell label="Einsatzort / Adresse" value={data.einsatzort} width="50%" />
              <FieldCell label="Objekt / Gebäude" value={data.objekt} width="50%" />
            </View>
            <View style={styles.fieldRow}>
              <FieldCell label="Alarmierungsart" value={data.alarmierungsart} width="50%" />
              <FieldCell label="Stichwort / Meldebild" value={data.stichwort} width="50%" />
            </View>
          </View>
        </View>

        {/* 2. Zeitverlauf */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>2</Text>
            <Text style={styles.sectionTitle}>Zeitverlauf</Text>
            <View style={styles.sectionLine} />
          </View>
          <View style={styles.fieldGrid}>
            <View style={styles.fieldRow}>
              <FieldCell label="Alarmierung" value={data.zeitAlarm} mono highlight width="50%" />
              <FieldCell label="Eintreffen" value={data.zeitEintreffen} mono highlight width="50%" />
            </View>
          </View>
        </View>

        {/* 3. Lagebild */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>3</Text>
            <Text style={styles.sectionTitle}>Lagebild</Text>
            <View style={styles.sectionLine} />
          </View>
          <View style={styles.fieldGrid}>
            <View style={styles.fieldRow}>
              <FieldCell label="Lage bei Eintreffen" value={data.lageEintreffen} width="100%" />
            </View>
            <View style={styles.fieldRow}>
              <View style={[styles.field, { width: '100%' }]}>
                <Text style={styles.fieldLabel}>Getroffene Massnahmen</Text>
                {Array.isArray(data.massnahmen) ? (
                  data.massnahmen.map((m, i) => (
                    <Text key={i} style={[styles.fieldValue, { fontSize: 8, marginBottom: 1.5 }]}>• {m}</Text>
                  ))
                ) : (
                  <Text style={styles.fieldValue}>{data.massnahmen || '—'}</Text>
                )}
              </View>
            </View>
          </View>
        </View>

        {/* 4. Lageplan-Karte */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>4</Text>
            <Text style={styles.sectionTitle}>Lageplan / Skizze</Text>
            <View style={styles.sectionLine} />
          </View>
          {data.mapScreenshot ? (
            <Image src={data.mapScreenshot} style={{ width: '100%', height: 'auto', maxHeight: '80mm', borderWidth: 1, borderColor: '#d0d0d0', borderRadius: 4 }} />
          ) : (
            <View style={styles.mapContainer}>
              <Text style={styles.mapPlaceholder}>Lageplan aus app.lageplan.ch{'\n'}({data.einsatzort})</Text>
            </View>
          )}
        </View>

        {/* 5. Eingesetzte Mittel */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>5</Text>
            <Text style={styles.sectionTitle}>Eingesetzte Mittel</Text>
            <View style={styles.sectionLine} />
          </View>
          <View style={styles.fieldGrid}>
            <View style={styles.tableHeader}>
              <Text style={[styles.tableHeaderCell, { width: '25%' }]}>Fahrzeug / Mittel</Text>
              <Text style={[styles.tableHeaderCell, { width: '10%' }]}>Pers.</Text>
              <Text style={[styles.tableHeaderCell, { width: '15%' }]}>Ausrücken</Text>
              <Text style={[styles.tableHeaderCell, { width: '15%' }]}>Eintreffen</Text>
              <Text style={[styles.tableHeaderCell, { width: '35%' }]}>Auftrag / Bemerkung</Text>
            </View>
            {(data.fahrzeuge.length > 0 ? data.fahrzeuge : [{ name: '', pers: '', ausruecken: '', eintreffen: '', auftrag: '' }]).map((fz, i) => (
              <View key={i} style={[styles.tableRow, i % 2 === 1 ? styles.tableRowEven : {}]}>
                <Text style={[styles.tableCell, { width: '25%' }]}>{fz.name}</Text>
                <Text style={[styles.tableCell, { width: '10%' }]}>{fz.pers}</Text>
                <Text style={[styles.tableCell, { width: '15%' }]}>{fz.ausruecken}</Text>
                <Text style={[styles.tableCell, { width: '15%' }]}>{fz.eintreffen}</Text>
                <Text style={[styles.tableCell, { width: '35%' }]}>{fz.auftrag}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* 6. Bemerkungen */}
        <View style={styles.section}>
          <View style={styles.sectionHeader}>
            <Text style={styles.sectionNumber}>6</Text>
            <Text style={styles.sectionTitle}>Bemerkungen / Besondere Vorkommnisse</Text>
            <View style={styles.sectionLine} />
          </View>
          <View style={styles.notesBox}>
            <Text style={styles.notesText}>{data.bemerkungen || ''}</Text>
          </View>
        </View>

        {/* Unterschriften */}
        <View style={styles.signatureBlock}>
          <View style={styles.signatureField}>
            <View style={styles.signatureLine} />
            <Text style={styles.signatureLabel}>Einsatzleiter/in · {data.einsatzleiter}</Text>
          </View>
          <View style={styles.signatureField}>
            <View style={styles.signatureLine} />
            <Text style={styles.signatureLabel}>Rapport erstellt durch · {data.rapporteur}</Text>
          </View>
          <View style={styles.signatureField}>
            <View style={styles.signatureLine} />
            <Text style={styles.signatureLabel}>Datum / Visum Kdt</Text>
          </View>
        </View>

        {/* Footer with QR code */}
        <View style={styles.footer} fixed>
          <View>
            <Text>Erstellt: {data.datum} {data.uhrzeit} · {data.organisation}</Text>
            <Text>Projekt: {data.reportNumber} · Standort: {data.einsatzort}</Text>
          </View>
          {data.qrCodeUrl ? (
            <View style={{ alignItems: 'center' }}>
              <Image src={data.qrCodeUrl} style={{ width: 45, height: 45 }} />
              <Text style={{ fontSize: 5, color: '#888', marginTop: 1 }}>Online-Rapport</Text>
            </View>
          ) : null}
          <View style={{ textAlign: 'right' }}>
            <Text>app.lageplan.ch</Text>
            <Text render={({ pageNumber, totalPages }: { pageNumber: number; totalPages: number }) => `Seite ${pageNumber}/${totalPages}`} />
          </View>
        </View>
      </Page>
    </Document>
  )
}
