/**
 * VIP Schedule PDF Generator
 *
 * Professional itinerary document designed for VIP guests.
 * Fully customizable through PDF Settings.
 */

import {
  Document,
  Page,
  Text,
  View,
  StyleSheet,
  Font,
  Image,
} from '@react-pdf/renderer';
import { PdfSettings } from '@/types/settings';

// Register fonts for professional typography
Font.register({
  family: 'Helvetica',
  fonts: [
    { src: 'Helvetica' },
    { src: 'Helvetica-Bold', fontWeight: 'bold' },
  ],
});

interface VIP {
  id: string;
  name: string;
  organization: string | null;
  department: string;
  arrivalMode: string;
  expectedArrival: string | null;
  airportPickup: boolean;
  venueTransport: boolean;
  notes: string | null;
  flights: Array<{
    id: string;
    flightNumber: string;
    departureAirport: string;
    arrivalAirport: string;
    scheduledDeparture: string | null;
    scheduledArrival: string | null;
    status: string | null;
  }>;
}

interface PDFScheduleEvent {
  id: string;
  title: string;
  pickupLocation?: string | null;
  dropoffLocation?: string | null;
  location?: string | null;
  startTime: string;
  endTime: string;
  type: string;
  status: string;
  description?: string | null;
  driver?: {
    id: string;
    name: string;
  } | null;
  vehicle?: {
    id: string;
    name: string;
    type: string;
    seatCapacity?: number;
  } | null;
}

interface VIPSchedulePDFProps {
  vip: VIP;
  events: PDFScheduleEvent[];
  settings?: PdfSettings | null;
}

// Create dynamic styles based on settings
const createStyles = (accentColor: string = '#2c3e50', pageSize: 'LETTER' | 'A4' = 'LETTER') =>
  StyleSheet.create({
    page: {
      padding: 50,
      paddingBottom: 80,
      fontSize: 10,
      fontFamily: 'Helvetica',
      backgroundColor: '#ffffff',
      color: '#333333',
    },

    // Watermark
    watermark: {
      position: 'absolute',
      top: '40%',
      left: '50%',
      transform: 'translate(-50%, -50%) rotate(-45deg)',
      fontSize: 72,
      color: '#888888',
      opacity: 0.2,
      fontWeight: 'bold',
      zIndex: 0,
    },

    // Logo
    logoContainer: {
      marginBottom: 15,
      flexDirection: 'row',
      justifyContent: 'center',
    },
    logo: {
      maxWidth: 150,
      maxHeight: 60,
      objectFit: 'contain',
    },

    // Header
    header: {
      marginBottom: 30,
      borderBottom: `2 solid ${accentColor}`,
      paddingBottom: 20,
    },
    orgName: {
      fontSize: 10,
      color: '#7f8c8d',
      textTransform: 'uppercase',
      letterSpacing: 2,
      marginBottom: 8,
    },
    title: {
      fontSize: 28,
      fontWeight: 'bold',
      color: accentColor,
      marginBottom: 4,
    },
    subtitle: {
      fontSize: 12,
      color: '#7f8c8d',
    },
    tagline: {
      fontSize: 10,
      color: '#95a5a6',
      marginTop: 4,
      fontStyle: 'italic',
    },

    // Custom messages
    customMessage: {
      fontSize: 10,
      color: '#7f8c8d',
      marginTop: 10,
      padding: 10,
      backgroundColor: '#f8f9fa',
      borderLeft: `3 solid ${accentColor}`,
    },

    // Timestamp
    timestampBar: {
      marginTop: 15,
      paddingTop: 10,
      borderTop: '1 solid #ecf0f1',
      flexDirection: 'row',
      justifyContent: 'space-between',
    },
    timestamp: {
      fontSize: 8,
      color: '#95a5a6',
    },

    // Sections
    section: {
      marginBottom: 25,
    },
    sectionTitle: {
      fontSize: 11,
      fontWeight: 'bold',
      color: accentColor,
      textTransform: 'uppercase',
      letterSpacing: 1,
      marginBottom: 12,
      paddingBottom: 6,
      borderBottom: `2 solid ${accentColor}`,
    },

    // Flight info
    flightCard: {
      backgroundColor: '#f8f9fa',
      padding: 15,
      marginBottom: 10,
      borderLeft: `3 solid ${accentColor}`,
    },
    flightNumber: {
      fontSize: 14,
      fontWeight: 'bold',
      color: '#2c3e50',
      marginBottom: 6,
    },
    flightRoute: {
      fontSize: 11,
      color: '#34495e',
      marginBottom: 4,
    },
    flightTime: {
      fontSize: 10,
      color: '#7f8c8d',
    },

    // Day header
    dayHeader: {
      backgroundColor: accentColor,
      color: '#ffffff',
      padding: 10,
      marginBottom: 0,
      marginTop: 15,
    },
    dayHeaderText: {
      fontSize: 12,
      fontWeight: 'bold',
      color: '#ffffff',
    },

    // Schedule table
    scheduleTable: {
      borderLeft: '1 solid #dee2e6',
      borderRight: '1 solid #dee2e6',
    },
    scheduleRow: {
      flexDirection: 'row',
      borderBottom: '1 solid #dee2e6',
      minHeight: 45,
    },
    scheduleRowAlt: {
      backgroundColor: '#f8f9fa',
    },
    timeColumn: {
      width: '18%',
      padding: 10,
      borderRight: '1 solid #dee2e6',
      justifyContent: 'center',
    },
    timeText: {
      fontSize: 10,
      fontWeight: 'bold',
      color: '#2c3e50',
    },
    timeEndText: {
      fontSize: 8,
      color: '#95a5a6',
      marginTop: 2,
    },
    detailsColumn: {
      width: '82%',
      padding: 10,
      justifyContent: 'center',
    },
    eventTitle: {
      fontSize: 11,
      fontWeight: 'bold',
      color: '#2c3e50',
      marginBottom: 4,
    },
    eventLocation: {
      fontSize: 9,
      color: '#7f8c8d',
      marginBottom: 3,
    },
    eventDriver: {
      fontSize: 9,
      color: accentColor,
    },
    eventDescription: {
      fontSize: 9,
      color: '#7f8c8d',
      marginTop: 4,
      fontStyle: 'italic',
    },

    // Notes section
    notesBox: {
      backgroundColor: '#fef9e7',
      padding: 15,
      borderLeft: '3 solid #f1c40f',
    },
    notesTitle: {
      fontSize: 10,
      fontWeight: 'bold',
      color: '#7d6608',
      marginBottom: 6,
    },
    notesText: {
      fontSize: 10,
      color: '#5d4e37',
      lineHeight: 1.5,
    },

    // Footer
    footer: {
      position: 'absolute',
      bottom: 30,
      left: 50,
      right: 50,
      paddingTop: 15,
      borderTop: '1 solid #dee2e6',
    },
    footerContent: {
      flexDirection: 'row',
      justifyContent: 'space-between',
    },
    footerLeft: {
      maxWidth: '60%',
    },
    footerTitle: {
      fontSize: 9,
      fontWeight: 'bold',
      color: '#2c3e50',
      marginBottom: 4,
    },
    footerContact: {
      fontSize: 8,
      color: '#7f8c8d',
      marginBottom: 2,
    },
    footerRight: {
      textAlign: 'right',
    },
    pageNumber: {
      fontSize: 8,
      color: '#95a5a6',
    },

    // Empty state
    emptyState: {
      textAlign: 'center',
      padding: 30,
      color: '#95a5a6',
      fontSize: 11,
    },
  });

export function VIPSchedulePDF({
  vip,
  events,
  settings,
}: VIPSchedulePDFProps) {
  // Default settings if not provided
  const config = settings || {
    organizationName: 'VIP Transportation Services',
    accentColor: '#2c3e50',
    contactEmail: 'coordinator@example.com',
    contactPhone: '(555) 123-4567',
    contactLabel: 'Questions or Changes?',
    showDraftWatermark: false,
    showConfidentialWatermark: false,
    showTimestamp: true,
    showAppUrl: false,
    pageSize: 'LETTER' as const,
    showFlightInfo: true,
    showDriverNames: true,
    showVehicleNames: true,
    showVipNotes: true,
    showEventDescriptions: true,
    logoUrl: null,
    tagline: null,
    headerMessage: null,
    footerMessage: null,
    secondaryContactName: null,
    secondaryContactPhone: null,
  };

  const styles = createStyles(config.accentColor, config.pageSize);

  // Format generation timestamp
  const generatedAt = new Date().toLocaleString('en-US', {
    month: 'long',
    day: 'numeric',
    year: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  });

  // Filter out cancelled events and sort by start time
  const activeEvents = events
    .filter(e => e.status !== 'CANCELLED')
    .sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());

  // Group events by day
  const eventsByDay = activeEvents.reduce((acc, event) => {
    const date = new Date(event.startTime).toLocaleDateString('en-US', {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric',
    });
    if (!acc[date]) {
      acc[date] = [];
    }
    acc[date].push(event);
    return acc;
  }, {} as Record<string, PDFScheduleEvent[]>);

  // Format time helper
  const formatTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
    });
  };

  // Format location for display
  const formatLocation = (event: PDFScheduleEvent) => {
    if (event.type === 'TRANSPORT') {
      const pickup = event.pickupLocation || 'Pickup location';
      const dropoff = event.dropoffLocation || 'Destination';
      return `From: ${pickup}  →  To: ${dropoff}`;
    }
    return event.location || '';
  };

  return (
    <Document>
      <Page size={config.pageSize} style={styles.page}>
        {/* Watermarks */}
        {config.showDraftWatermark && (
          <View style={styles.watermark} fixed>
            <Text>DRAFT</Text>
          </View>
        )}
        {config.showConfidentialWatermark && (
          <View style={styles.watermark} fixed>
            <Text>CONFIDENTIAL</Text>
          </View>
        )}

        {/* Header */}
        <View style={styles.header}>
          {/* Logo */}
          {config.logoUrl && (
            <View style={styles.logoContainer}>
              <Image src={config.logoUrl} style={styles.logo} />
            </View>
          )}

          <Text style={styles.orgName}>{config.organizationName}</Text>
          <Text style={styles.title}>Itinerary for {vip.name}</Text>
          {vip.organization && (
            <Text style={styles.subtitle}>{vip.organization}</Text>
          )}
          {config.tagline && (
            <Text style={styles.tagline}>{config.tagline}</Text>
          )}

          {/* Custom Header Message */}
          {config.headerMessage && (
            <Text style={styles.customMessage}>{config.headerMessage}</Text>
          )}

          {/* Timestamp bar */}
          {(config.showTimestamp || config.showAppUrl) && (
            <View style={styles.timestampBar}>
              {config.showTimestamp && (
                <Text style={styles.timestamp}>
                  Generated: {generatedAt}
                </Text>
              )}
              {config.showAppUrl && (
                <Text style={styles.timestamp}>
                  Latest version: {window.location.origin}
                </Text>
              )}
            </View>
          )}
        </View>

        {/* Flight Information */}
        {config.showFlightInfo && vip.flights && vip.flights.length > 0 && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>Flight Information</Text>
            {vip.flights.map((flight) => (
              <View key={flight.id} style={styles.flightCard}>
                <Text style={styles.flightNumber}>{flight.flightNumber}</Text>
                <Text style={styles.flightRoute}>
                  {flight.departureAirport} → {flight.arrivalAirport}
                </Text>
                {flight.scheduledDeparture && (
                  <Text style={styles.flightTime}>
                    Departs: {new Date(flight.scheduledDeparture).toLocaleString('en-US', {
                      weekday: 'short',
                      month: 'short',
                      day: 'numeric',
                      hour: 'numeric',
                      minute: '2-digit',
                    })}
                  </Text>
                )}
                {flight.scheduledArrival && (
                  <Text style={styles.flightTime}>
                    Arrives: {new Date(flight.scheduledArrival).toLocaleString('en-US', {
                      weekday: 'short',
                      month: 'short',
                      day: 'numeric',
                      hour: 'numeric',
                      minute: '2-digit',
                    })}
                  </Text>
                )}
              </View>
            ))}
          </View>
        )}

        {/* Schedule */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>Your Schedule</Text>

          {activeEvents.length === 0 ? (
            <Text style={styles.emptyState}>
              No scheduled activities at this time.
            </Text>
          ) : (
            Object.entries(eventsByDay).map(([date, dayEvents]) => (
              <View key={date} wrap={false}>
                {/* Day Header */}
                <View style={styles.dayHeader}>
                  <Text style={styles.dayHeaderText}>{date}</Text>
                </View>

                {/* Events Table */}
                <View style={styles.scheduleTable}>
                  {dayEvents.map((event, index) => (
                    <View
                      key={event.id}
                      style={[
                        styles.scheduleRow,
                        index % 2 === 1 ? styles.scheduleRowAlt : {},
                      ]}
                    >
                      {/* Time Column */}
                      <View style={styles.timeColumn}>
                        <Text style={styles.timeText}>{formatTime(event.startTime)}</Text>
                        <Text style={styles.timeEndText}>to {formatTime(event.endTime)}</Text>
                      </View>

                      {/* Details Column */}
                      <View style={styles.detailsColumn}>
                        <Text style={styles.eventTitle}>{event.title}</Text>

                        {formatLocation(event) && (
                          <Text style={styles.eventLocation}>{formatLocation(event)}</Text>
                        )}

                        {event.type === 'TRANSPORT' && event.driver && config.showDriverNames && (
                          <Text style={styles.eventDriver}>
                            Your driver: {event.driver.name}
                            {event.vehicle && config.showVehicleNames ? ` (${event.vehicle.name})` : ''}
                          </Text>
                        )}

                        {event.description && config.showEventDescriptions && (
                          <Text style={styles.eventDescription}>{event.description}</Text>
                        )}
                      </View>
                    </View>
                  ))}
                </View>
              </View>
            ))
          )}
        </View>

        {/* Special Notes */}
        {config.showVipNotes && vip.notes && (
          <View style={styles.section}>
            <View style={styles.notesBox}>
              <Text style={styles.notesTitle}>Important Notes</Text>
              <Text style={styles.notesText}>{vip.notes}</Text>
            </View>
          </View>
        )}

        {/* Custom Footer Message */}
        {config.footerMessage && (
          <View style={styles.section}>
            <Text style={styles.customMessage}>{config.footerMessage}</Text>
          </View>
        )}

        {/* Footer */}
        <View style={styles.footer} fixed>
          <View style={styles.footerContent}>
            <View style={styles.footerLeft}>
              <Text style={styles.footerTitle}>{config.contactLabel}</Text>
              <Text style={styles.footerContact}>{config.contactEmail}</Text>
              <Text style={styles.footerContact}>{config.contactPhone}</Text>
              {config.secondaryContactName && (
                <Text style={styles.footerContact}>
                  {config.secondaryContactName}
                  {config.secondaryContactPhone ? ` - ${config.secondaryContactPhone}` : ''}
                </Text>
              )}
            </View>
            <View style={styles.footerRight}>
              <Text
                style={styles.pageNumber}
                render={({ pageNumber, totalPages }) =>
                  `Page ${pageNumber} of ${totalPages}`
                }
              />
            </View>
          </View>
        </View>
      </Page>
    </Document>
  );
}
