import { useState, useRef, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import toast from 'react-hot-toast';
import { pdf } from '@react-pdf/renderer';
import { VIPSchedulePDF } from '@/components/VIPSchedulePDF';
import {
  Settings,
  FileText,
  Upload,
  Palette,
  X,
  Loader2,
  Eye,
  ChevronDown,
  ChevronUp,
  Globe,
} from 'lucide-react';
import {
  usePdfSettings,
  useUpdatePdfSettings,
  useUploadLogo,
  useDeleteLogo,
} from '@/hooks/useSettings';
import { UpdatePdfSettingsDto, PageSize } from '@/types/settings';

export function PdfSettingsSection() {
  const { data: settings, isLoading: loadingSettings } = usePdfSettings();
  const updateSettings = useUpdatePdfSettings();
  const uploadLogo = useUploadLogo();
  const deleteLogo = useDeleteLogo();

  const [logoPreview, setLogoPreview] = useState<string | null>(null);
  const [expandedSections, setExpandedSections] = useState({
    branding: true,
    contact: false,
    document: false,
    content: false,
    custom: false,
  });
  const fileInputRef = useRef<HTMLInputElement>(null);

  const { register, handleSubmit, watch, reset, setValue } = useForm<UpdatePdfSettingsDto>();

  const accentColor = watch('accentColor');

  // Update form when settings load
  useEffect(() => {
    if (settings) {
      // Map PdfSettings to UpdatePdfSettingsDto (exclude id, createdAt, updatedAt, logoUrl)
      const formData: UpdatePdfSettingsDto = {
        organizationName: settings.organizationName,
        accentColor: settings.accentColor,
        tagline: settings.tagline || undefined,
        contactEmail: settings.contactEmail,
        contactPhone: settings.contactPhone,
        secondaryContactName: settings.secondaryContactName || undefined,
        secondaryContactPhone: settings.secondaryContactPhone || undefined,
        contactLabel: settings.contactLabel,
        showDraftWatermark: settings.showDraftWatermark,
        showConfidentialWatermark: settings.showConfidentialWatermark,
        showTimestamp: settings.showTimestamp,
        showAppUrl: settings.showAppUrl,
        pageSize: settings.pageSize,
        timezone: settings.timezone,
        showFlightInfo: settings.showFlightInfo,
        showDriverNames: settings.showDriverNames,
        showVehicleNames: settings.showVehicleNames,
        showVipNotes: settings.showVipNotes,
        showEventDescriptions: settings.showEventDescriptions,
        headerMessage: settings.headerMessage || undefined,
        footerMessage: settings.footerMessage || undefined,
      };
      reset(formData);
    }
  }, [settings, reset]);

  const toggleSection = (section: keyof typeof expandedSections) => {
    setExpandedSections(prev => ({
      ...prev,
      [section]: !prev[section],
    }));
  };

  const onSubmit = async (data: UpdatePdfSettingsDto) => {
    try {
      await updateSettings.mutateAsync(data);
      toast.success('PDF settings saved successfully');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Failed to save settings');
    }
  };

  const handleLogoUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file size (2MB)
    if (file.size > 2 * 1024 * 1024) {
      toast.error('Logo file must be less than 2MB');
      return;
    }

    // Validate file type
    if (!['image/png', 'image/jpeg', 'image/svg+xml'].includes(file.type)) {
      toast.error('Logo must be PNG, JPG, or SVG');
      return;
    }

    // Show preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setLogoPreview(reader.result as string);
    };
    reader.readAsDataURL(file);

    // Upload
    try {
      await uploadLogo.mutateAsync(file);
      toast.success('Logo uploaded successfully');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Failed to upload logo');
      setLogoPreview(null);
    }
  };

  const handleDeleteLogo = async () => {
    if (!confirm('Remove logo from PDF templates?')) return;

    try {
      await deleteLogo.mutateAsync();
      setLogoPreview(null);
      toast.success('Logo removed');
    } catch (error: any) {
      toast.error(error.response?.data?.message || 'Failed to remove logo');
    }
  };

  const handlePreview = async () => {
    if (!settings) {
      toast.error('Settings not loaded yet');
      return;
    }

    try {
      toast.loading('Generating preview PDF...', { id: 'pdf-preview' });

      // Mock VIP data
      const mockVIP = {
        id: 'sample-id',
        name: 'John Sample',
        organization: 'Sample Corporation',
        department: 'OFFICE_OF_DEVELOPMENT',
        arrivalMode: 'FLIGHT',
        expectedArrival: null,
        airportPickup: true,
        venueTransport: true,
        notes: 'This is a sample itinerary to preview your PDF customization settings.',
        flights: [
          {
            id: 'flight-1',
            flightNumber: 'AA1234',
            departureAirport: 'JFK',
            arrivalAirport: 'LAX',
            scheduledDeparture: new Date(Date.now() + 86400000).toISOString(), // Tomorrow
            scheduledArrival: new Date(Date.now() + 86400000 + 21600000).toISOString(), // Tomorrow + 6 hours
            status: 'scheduled',
          },
        ],
      };

      // Mock events
      const tomorrow = new Date(Date.now() + 86400000);
      const mockEvents = [
        {
          id: 'event-1',
          title: 'Airport Pickup',
          pickupLocation: 'LAX Terminal 4',
          dropoffLocation: 'Grand Hotel',
          location: null,
          startTime: new Date(tomorrow.getTime() + 25200000).toISOString(), // 10 AM
          endTime: new Date(tomorrow.getTime() + 28800000).toISOString(), // 11 AM
          type: 'TRANSPORT',
          status: 'SCHEDULED',
          description: 'Transportation from airport to hotel',
          driver: { id: 'driver-1', name: 'Michael Driver' },
          vehicle: { id: 'vehicle-1', name: 'Blue Van', type: 'VAN', seatCapacity: 12 },
        },
        {
          id: 'event-2',
          title: 'Welcome Lunch',
          pickupLocation: null,
          dropoffLocation: null,
          location: 'Grand Ballroom',
          startTime: new Date(tomorrow.getTime() + 43200000).toISOString(), // 12 PM
          endTime: new Date(tomorrow.getTime() + 48600000).toISOString(), // 1:30 PM
          type: 'MEAL',
          status: 'SCHEDULED',
          description: 'Networking lunch with other VIP guests and leadership',
          driver: null,
          vehicle: null,
        },
        {
          id: 'event-3',
          title: 'Opening Ceremony',
          pickupLocation: null,
          dropoffLocation: null,
          location: 'Main Arena',
          startTime: new Date(tomorrow.getTime() + 54000000).toISOString(), // 3 PM
          endTime: new Date(tomorrow.getTime() + 61200000).toISOString(), // 5 PM
          type: 'EVENT',
          status: 'SCHEDULED',
          description: 'Official opening ceremony with keynote speakers',
          driver: null,
          vehicle: null,
        },
      ];

      // Generate PDF with current settings
      const blob = await pdf(
        <VIPSchedulePDF vip={mockVIP} events={mockEvents} settings={settings} />
      ).toBlob();

      // Open in new tab
      const url = URL.createObjectURL(blob);
      window.open(url, '_blank');
      URL.revokeObjectURL(url);

      toast.success('Preview generated!', { id: 'pdf-preview' });
    } catch (error: any) {
      console.error('Failed to generate preview:', error);
      toast.error('Failed to generate preview', { id: 'pdf-preview' });
    }
  };

  if (loadingSettings) {
    return (
      <div className="bg-card border border-border shadow-soft rounded-lg p-6 mb-8 transition-colors">
        <div className="flex items-center justify-center py-8">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      </div>
    );
  }

  const currentLogo = logoPreview || settings?.logoUrl;

  return (
    <div className="bg-card border border-border shadow-soft rounded-lg p-6 mb-8 transition-colors">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center">
          <FileText className="h-5 w-5 text-purple-600 mr-2" />
          <h2 className="text-lg font-medium text-foreground">PDF Customization</h2>
        </div>
        <button
          onClick={handlePreview}
          className="inline-flex items-center px-3 py-2 text-sm border border-input text-foreground rounded-md hover:bg-accent transition-colors"
        >
          <Eye className="h-4 w-4 mr-1" />
          Preview Sample PDF
        </button>
      </div>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        {/* Branding Section */}
        <div className="border border-border rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => toggleSection('branding')}
            className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
          >
            <div className="flex items-center">
              <Palette className="h-4 w-4 mr-2 text-muted-foreground" />
              <span className="font-medium text-foreground">Branding</span>
            </div>
            {expandedSections.branding ? (
              <ChevronUp className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-4 w-4 text-muted-foreground" />
            )}
          </button>

          {expandedSections.branding && (
            <div className="p-4 space-y-4">
              {/* Organization Name */}
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Organization Name
                </label>
                <input
                  type="text"
                  {...register('organizationName')}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="VIP Coordinator"
                />
              </div>

              {/* Logo Upload */}
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Organization Logo
                </label>
                <div className="flex items-start gap-4">
                  {currentLogo && (
                    <div className="relative w-32 h-32 border border-border rounded-lg overflow-hidden bg-white p-2">
                      <img
                        src={currentLogo}
                        alt="Logo"
                        className="w-full h-full object-contain"
                      />
                      <button
                        type="button"
                        onClick={handleDeleteLogo}
                        className="absolute top-1 right-1 p-1 bg-red-600 text-white rounded-full hover:bg-red-700 transition-colors"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </div>
                  )}
                  <div className="flex-1">
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/png,image/jpeg,image/svg+xml"
                      onChange={handleLogoUpload}
                      className="hidden"
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      disabled={uploadLogo.isPending}
                      className="inline-flex items-center px-4 py-2 border border-input text-foreground rounded-md hover:bg-accent disabled:opacity-50 transition-colors"
                    >
                      {uploadLogo.isPending ? (
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                      ) : (
                        <Upload className="h-4 w-4 mr-2" />
                      )}
                      {currentLogo ? 'Change Logo' : 'Upload Logo'}
                    </button>
                    <p className="text-xs text-muted-foreground mt-1">
                      PNG, JPG, or SVG. Max 2MB.
                    </p>
                  </div>
                </div>
              </div>

              {/* Accent Color */}
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Accent Color
                </label>
                <div className="flex items-center gap-3">
                  <input
                    type="color"
                    value={accentColor || '#2c3e50'}
                    onChange={(e) => setValue('accentColor', e.target.value)}
                    className="h-10 w-20 border border-input rounded cursor-pointer"
                  />
                  <input
                    type="text"
                    {...register('accentColor')}
                    className="flex-1 px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary font-mono text-sm"
                    placeholder="#2c3e50"
                  />
                  <div
                    className="h-10 w-10 rounded border border-input"
                    style={{ backgroundColor: accentColor || '#2c3e50' }}
                  />
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  Used for headers, section titles, and flight card borders
                </p>
              </div>

              {/* Tagline */}
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Tagline (Optional)
                </label>
                <input
                  type="text"
                  {...register('tagline')}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="Excellence in VIP Transportation"
                />
              </div>
            </div>
          )}
        </div>

        {/* Contact Information Section */}
        <div className="border border-border rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => toggleSection('contact')}
            className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
          >
            <div className="flex items-center">
              <Settings className="h-4 w-4 mr-2 text-muted-foreground" />
              <span className="font-medium text-foreground">Contact Information</span>
            </div>
            {expandedSections.contact ? (
              <ChevronUp className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-4 w-4 text-muted-foreground" />
            )}
          </button>

          {expandedSections.contact && (
            <div className="p-4 space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Contact Email
                  </label>
                  <input
                    type="email"
                    {...register('contactEmail')}
                    className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Contact Phone
                  </label>
                  <input
                    type="tel"
                    {...register('contactPhone')}
                    className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Secondary Contact Name (Optional)
                  </label>
                  <input
                    type="text"
                    {...register('secondaryContactName')}
                    className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Secondary Contact Phone (Optional)
                  </label>
                  <input
                    type="tel"
                    {...register('secondaryContactPhone')}
                    className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Contact Section Label
                </label>
                <input
                  type="text"
                  {...register('contactLabel')}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="Questions or Changes?"
                />
              </div>
            </div>
          )}
        </div>

        {/* Document Options Section */}
        <div className="border border-border rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => toggleSection('document')}
            className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
          >
            <div className="flex items-center">
              <FileText className="h-4 w-4 mr-2 text-muted-foreground" />
              <span className="font-medium text-foreground">Document Options</span>
            </div>
            {expandedSections.document ? (
              <ChevronUp className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-4 w-4 text-muted-foreground" />
            )}
          </button>

          {expandedSections.document && (
            <div className="p-4 space-y-3">
              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showDraftWatermark')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Draft Watermark</div>
                  <div className="text-sm text-muted-foreground">
                    Show diagonal "DRAFT" watermark on all pages
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showConfidentialWatermark')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Confidential Watermark</div>
                  <div className="text-sm text-muted-foreground">
                    Show diagonal "CONFIDENTIAL" watermark on all pages
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showTimestamp')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show Timestamp</div>
                  <div className="text-sm text-muted-foreground">
                    Display "Generated on [date]" in footer
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showAppUrl')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show App URL</div>
                  <div className="text-sm text-muted-foreground">
                    Display system URL in footer (not recommended for VIPs)
                  </div>
                </div>
              </label>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">
                  Page Size
                </label>
                <select
                  {...register('pageSize')}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  <option value={PageSize.LETTER}>Letter (8.5" x 11")</option>
                  <option value={PageSize.A4}>A4 (210mm x 297mm)</option>
                </select>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-2">
                  <Globe className="h-4 w-4 inline mr-1" />
                  System Timezone
                </label>
                <select
                  {...register('timezone')}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  <optgroup label="US Timezones">
                    <option value="America/New_York">Eastern Time (ET)</option>
                    <option value="America/Chicago">Central Time (CT)</option>
                    <option value="America/Denver">Mountain Time (MT)</option>
                    <option value="America/Phoenix">Arizona (no DST)</option>
                    <option value="America/Los_Angeles">Pacific Time (PT)</option>
                    <option value="America/Anchorage">Alaska Time (AKT)</option>
                    <option value="Pacific/Honolulu">Hawaii Time (HT)</option>
                  </optgroup>
                  <optgroup label="International">
                    <option value="UTC">UTC (Coordinated Universal Time)</option>
                    <option value="Europe/London">London (GMT/BST)</option>
                    <option value="Europe/Paris">Paris (CET/CEST)</option>
                    <option value="Europe/Berlin">Berlin (CET/CEST)</option>
                    <option value="Asia/Tokyo">Tokyo (JST)</option>
                    <option value="Asia/Shanghai">Shanghai (CST)</option>
                    <option value="Australia/Sydney">Sydney (AEST/AEDT)</option>
                  </optgroup>
                </select>
                <p className="text-xs text-muted-foreground mt-1">
                  All times in correspondence and exports will use this timezone
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Content Toggles Section */}
        <div className="border border-border rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => toggleSection('content')}
            className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
          >
            <div className="flex items-center">
              <Settings className="h-4 w-4 mr-2 text-muted-foreground" />
              <span className="font-medium text-foreground">Content Display</span>
            </div>
            {expandedSections.content ? (
              <ChevronUp className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-4 w-4 text-muted-foreground" />
            )}
          </button>

          {expandedSections.content && (
            <div className="p-4 space-y-3">
              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showFlightInfo')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show Flight Information</div>
                  <div className="text-sm text-muted-foreground">
                    Display flight numbers, times, and airports
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showDriverNames')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show Driver Names</div>
                  <div className="text-sm text-muted-foreground">
                    Display assigned driver names in schedule
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showVehicleNames')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show Vehicle Names</div>
                  <div className="text-sm text-muted-foreground">
                    Display assigned vehicle names in schedule
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showVipNotes')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show VIP Notes</div>
                  <div className="text-sm text-muted-foreground">
                    Display notes and special requirements
                  </div>
                </div>
              </label>

              <label className="flex items-center gap-3 p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors cursor-pointer">
                <input
                  type="checkbox"
                  {...register('showEventDescriptions')}
                  className="h-4 w-4 text-primary border-input rounded focus:ring-2 focus:ring-primary"
                />
                <div>
                  <div className="font-medium text-foreground">Show Event Descriptions</div>
                  <div className="text-sm text-muted-foreground">
                    Display detailed descriptions for events
                  </div>
                </div>
              </label>
            </div>
          )}
        </div>

        {/* Custom Text Section */}
        <div className="border border-border rounded-lg overflow-hidden">
          <button
            type="button"
            onClick={() => toggleSection('custom')}
            className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
          >
            <div className="flex items-center">
              <FileText className="h-4 w-4 mr-2 text-muted-foreground" />
              <span className="font-medium text-foreground">Custom Messages</span>
            </div>
            {expandedSections.custom ? (
              <ChevronUp className="h-4 w-4 text-muted-foreground" />
            ) : (
              <ChevronDown className="h-4 w-4 text-muted-foreground" />
            )}
          </button>

          {expandedSections.custom && (
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Header Message (Optional)
                </label>
                <textarea
                  {...register('headerMessage')}
                  rows={2}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="Welcome to the 2026 Jamboree!"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Displayed at the top of the PDF (max 500 characters)
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-foreground mb-1">
                  Footer Message (Optional)
                </label>
                <textarea
                  {...register('footerMessage')}
                  rows={2}
                  className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="Thank you for being our guest"
                />
                <p className="text-xs text-muted-foreground mt-1">
                  Displayed at the bottom of the PDF (max 500 characters)
                </p>
              </div>
            </div>
          )}
        </div>

        {/* Save Button */}
        <div className="flex justify-end pt-4">
          <button
            type="submit"
            disabled={updateSettings.isPending}
            className="inline-flex items-center px-6 py-3 bg-primary text-white rounded-md hover:bg-primary/90 disabled:opacity-50 transition-colors font-medium"
          >
            {updateSettings.isPending ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Saving...
              </>
            ) : (
              'Save PDF Settings'
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
