import { html, css } from '@design.estate/dees-element';
import '@design.estate/dees-wcctools/demotools';
import '../../dees-panel/dees-panel.js';
import './component.js';
import type { DeesInputDatepicker } from './component.js';

export const demoFunc = () => html`
  <style>
    ${css`
      .demo-container {
        display: flex;
        flex-direction: column;
        gap: 24px;
        padding: 24px;
        max-width: 1200px;
        margin: 0 auto;
      }
      
      dees-panel {
        margin-bottom: 24px;
      }
      
      dees-panel:last-child {
        margin-bottom: 0;
      }
      
      .demo-output {
        margin-top: 16px;
        padding: 12px;
        background: rgba(0, 105, 242, 0.1);
        border-radius: 4px;
        font-size: 14px;
        font-family: monospace;
      }
      
      .date-group {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
      }
    `}
  </style>
  
  <div class="demo-container">
    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate basic date picker functionality
      const datePicker = elementArg.querySelector('dees-input-datepicker');
      
      if (datePicker) {
        datePicker.addEventListener('change', (event: CustomEvent) => {
          console.log('Basic date selected:', (event.target as DeesInputDatepicker).value);
        });
      }
    }}>
      <dees-panel .title=${'Basic Date Picker'} .subtitle=${'Simple date selection without time'}>
        <dees-input-datepicker
          label="Select Date"
          description="Choose a date from the calendar"
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate date and time picker
      const dateTimePicker = elementArg.querySelector('dees-input-datepicker[label="Event Date & Time"]');
      const appointmentPicker = elementArg.querySelector('dees-input-datepicker[label="Appointment"]');
      
      if (dateTimePicker) {
        dateTimePicker.addEventListener('change', (event: CustomEvent) => {
          const value = (event.target as DeesInputDatepicker).value;
          console.log('24h format datetime:', value);
        });
      }
      
      if (appointmentPicker) {
        appointmentPicker.addEventListener('change', (event: CustomEvent) => {
          const value = (event.target as DeesInputDatepicker).value;
          console.log('12h format datetime:', value);
        });
      }
    }}>
      <dees-panel .title=${'Date and Time Selection'} .subtitle=${'Date pickers with time selection in different formats'}>
        <dees-input-datepicker
          label="Event Date & Time"
          description="Select both date and time (24-hour format)"
          .enableTime=${true}
          timeFormat="24h"
        ></dees-input-datepicker>
        
        <dees-input-datepicker
          label="Appointment"
          description="Date and time with AM/PM selector (15-minute increments)"
          .enableTime=${true}
          timeFormat="12h"
          .minuteIncrement=${15}
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate timezone functionality
      const timezonePickers = elementArg.querySelectorAll('dees-input-datepicker');
      
      timezonePickers.forEach((picker) => {
        picker.addEventListener('change', (event: CustomEvent) => {
          const target = event.target as DeesInputDatepicker;
          console.log(`${target.label} value:`, target.value);
          const input = target.shadowRoot?.querySelector('.date-input') as HTMLInputElement;
          if (input) {
            console.log(`${target.label} formatted:`, input.value);
          }
        });
      });
    }}>
      <dees-panel .title=${'Timezone Support'} .subtitle=${'Date and time selection with timezone awareness'}>
        <dees-input-datepicker
          label="Meeting Time (with Timezone)"
          description="Select a date/time and timezone for the meeting"
          .enableTime=${true}
          .enableTimezone=${true}
          timeFormat="24h"
          timezone="America/New_York"
        ></dees-input-datepicker>
        
        <dees-input-datepicker
          label="Global Event Schedule"
          description="Schedule an event across different timezones"
          .enableTime=${true}
          .enableTimezone=${true}
          timeFormat="12h"
          timezone="Europe/London"
          .minuteIncrement=${30}
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate date constraints
      const futureDatePicker = elementArg.querySelector('dees-input-datepicker');
      
      if (futureDatePicker) {
        // Show the min/max constraints in action
        futureDatePicker.addEventListener('change', (event: CustomEvent) => {
          const value = (event.target as DeesInputDatepicker).value;
          if (value) {
            const selectedDate = new Date(value);
            const today = new Date();
            const daysDiff = Math.floor((selectedDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
            console.log(`Selected date is ${daysDiff} days from today`);
          }
        });
      }
    }}>
      <dees-panel .title=${'Date Range Constraints'} .subtitle=${'Limit selectable dates with min and max values'}>
        <dees-input-datepicker
          label="Future Date Only"
          description="Can only select dates from today to 90 days in the future"
          .minDate=${new Date().toISOString()}
          .maxDate=${new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString()}
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate different date formats
      const formatters = {
        'DD/MM/YYYY': 'European',
        'MM/DD/YYYY': 'US',
        'YYYY-MM-DD': 'ISO'
      };
      
      const datePickers = elementArg.querySelectorAll('dees-input-datepicker');
      datePickers.forEach((picker) => {
        picker.addEventListener('change', (event: CustomEvent) => {
          const target = event.target as DeesInputDatepicker;
          // Log the formatted value that's displayed in the input
          const input = target.shadowRoot?.querySelector('.date-input') as HTMLInputElement;
          if (input) {
            console.log(`${target.label} format:`, input.value);
          }
        });
      });
    }}>
      <dees-panel .title=${'Date Formats'} .subtitle=${'Different date display formats for various regions'}>
        <div class="date-group">
          <dees-input-datepicker
            label="European Format"
            dateFormat="DD/MM/YYYY"
            .value=${new Date().toISOString()}
          ></dees-input-datepicker>
          
          <dees-input-datepicker
            label="US Format"
            dateFormat="MM/DD/YYYY"
            .value=${new Date().toISOString()}
          ></dees-input-datepicker>
          
          <dees-input-datepicker
            label="ISO Format"
            dateFormat="YYYY-MM-DD"
            .value=${new Date().toISOString()}
          ></dees-input-datepicker>
        </div>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate required field validation
      const requiredPicker = elementArg.querySelector('dees-input-datepicker[required]');
      
      if (requiredPicker) {
        // Monitor blur events for validation
        requiredPicker.addEventListener('blur', () => {
          const picker = requiredPicker as DeesInputDatepicker;
          const value = picker.getValue();
          if (!value) {
            console.log('Required date field is empty');
          }
        });
      }
    }}>
      <dees-panel .title=${'Form States'} .subtitle=${'Required and disabled states'}>
        <dees-input-datepicker
          label="Birth Date"
          description="This field is required"
          .required=${true}
          placeholder="Select your birth date"
        ></dees-input-datepicker>
        
        <dees-input-datepicker
          label="Disabled Date"
          description="This field cannot be edited"
          .disabled=${true}
          .value=${new Date().toISOString()}
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Demonstrate week start customization
      const usPicker = elementArg.querySelector('dees-input-datepicker[label="US Calendar"]');
      const euPicker = elementArg.querySelector('dees-input-datepicker[label="EU Calendar"]');
      
      if (usPicker) {
        console.log('US Calendar starts on Sunday (0)');
      }
      if (euPicker) {
        console.log('EU Calendar starts on Monday (1)');
      }
    }}>
      <dees-panel .title=${'Calendar Customization'} .subtitle=${'Different week start days for various regions'}>
        <div class="date-group">
          <dees-input-datepicker
            label="US Calendar"
            description="Week starts on Sunday"
            .weekStartsOn=${0}
          ></dees-input-datepicker>
          
          <dees-input-datepicker
            label="EU Calendar"
            description="Week starts on Monday"
            .weekStartsOn=${1}
          ></dees-input-datepicker>
        </div>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Generate weekend dates for the current month
      const generateWeekends = () => {
        const weekends = [];
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth();
        
        // Get all weekends for current month
        const date = new Date(year, month, 1);
        while (date.getMonth() === month) {
          if (date.getDay() === 0 || date.getDay() === 6) {
            weekends.push(new Date(date).toISOString());
          }
          date.setDate(date.getDate() + 1);
        }
        return weekends;
      };
      
      const picker = elementArg.querySelector('dees-input-datepicker');
      if (picker) {
        picker.disabledDates = generateWeekends();
        console.log('Disabled weekend dates for current month');
      }
    }}>
      <dees-panel .title=${'Disabled Dates'} .subtitle=${'Calendar with specific dates disabled (weekends in current month)'}>
        <dees-input-datepicker
          label="Availability Calendar"
          description="Weekends are disabled for the current month"
        ></dees-input-datepicker>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Generate sample events for the calendar
      const today = new Date();
      const currentMonth = today.getMonth();
      const currentYear = today.getFullYear();
      
      const sampleEvents = [
        // Current week events
        {
          date: `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`,
          title: "Team Meeting",
          type: "info" as const,
          count: 2
        },
        {
          date: `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${(today.getDate() + 1).toString().padStart(2, '0')}`,
          title: "Project Deadline",
          type: "warning" as const
        },
        {
          date: `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${(today.getDate() + 2).toString().padStart(2, '0')}`,
          title: "Release Day",
          type: "success" as const
        },
        {
          date: `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${(today.getDate() + 5).toString().padStart(2, '0')}`,
          title: "Urgent Fix Required",
          type: "error" as const
        },
        // Multiple events on one day
        {
          date: `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}-${(today.getDate() + 7).toString().padStart(2, '0')}`,
          title: "Multiple Events Today",
          type: "info" as const,
          count: 5
        },
        // Next month event
        {
          date: `${currentYear}-${(currentMonth + 2).toString().padStart(2, '0')}-15`,
          title: "Future Planning Session",
          type: "info" as const
        }
      ];
      
      const picker = elementArg.querySelector('dees-input-datepicker');
      if (picker) {
        picker.events = sampleEvents;
        console.log('Calendar events loaded:', sampleEvents);
      }
    }}>
      <dees-panel .title=${'Calendar with Events'} .subtitle=${'Visual feedback for scheduled events'}>
        <dees-input-datepicker
          label="Event Calendar"
          description="Days with colored dots have events. Hover to see details."
        ></dees-input-datepicker>
        
        <div class="demo-output" style="margin-top: 16px;">
          <strong>Event Legend:</strong><br>
          <span style="color: #0969da;">● Info</span> | 
          <span style="color: #d29922;">● Warning</span> | 
          <span style="color: #2ea043;">● Success</span> | 
          <span style="color: #cf222e;">● Error</span><br>
          <em>Days with more than 3 events show a count badge</em>
        </div>
      </dees-panel>
    </dees-demowrapper>

    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      // Interactive event demonstration
      const picker = elementArg.querySelector('dees-input-datepicker');
      const output = elementArg.querySelector('#event-output');
      
      if (picker && output) {
        picker.addEventListener('change', (event: CustomEvent) => {
          const target = event.target as DeesInputDatepicker;
          const value = target.value;
          if (value) {
            const date = new Date(value);
            // Get the formatted value from the input element
            const input = target.shadowRoot?.querySelector('.date-input') as HTMLInputElement;
            const formattedValue = input?.value || 'N/A';
            output.innerHTML = `
              <strong>Event triggered!</strong><br>
              ISO Value: ${value}<br>
              Formatted: ${formattedValue}<br>
              Date object: ${date.toLocaleString()}
            `;
          } else {
            output.innerHTML = '<em>Date cleared</em>';
          }
        });
        
        picker.addEventListener('blur', () => {
          console.log('Datepicker lost focus');
        });
      }
    }}>
      <dees-panel .title=${'Event Handling'} .subtitle=${'Interactive demonstration of change events'}>
        <dees-input-datepicker
          label="Event Demo"
          description="Select a date to see the event details"
        ></dees-input-datepicker>
        
        <div id="event-output" class="demo-output">
          <em>Select a date to see event details...</em>
        </div>
      </dees-panel>
    </dees-demowrapper>
  </div>
`;