import { html, css, domtools, cssManager } from '@design.estate/dees-element';
import type { DeesForm } from './dees-form.js';
import '@design.estate/dees-wcctools/demotools';

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;
      }
      
      .form-output {
        margin-top: 16px;
        padding: 12px;
        background: ${cssManager.bdTheme('hsl(210 40% 96.1%)', 'hsl(215 20.2% 16.8%)')};
        border-radius: 6px;
        font-size: 14px;
        font-family: monospace;
        white-space: pre-wrap;
      }
      
      .status-message {
        margin-top: 16px;
        padding: 12px;
        border-radius: 6px;
        font-size: 14px;
      }
      
      .status-message.success {
        background: ${cssManager.bdTheme('hsl(142.1 70.6% 45.3% / 0.1)', 'hsl(142.1 70.6% 45.3% / 0.2)')};
        color: ${cssManager.bdTheme('hsl(142.1 70.6% 35.3%)', 'hsl(142.1 70.6% 65.3%)')};
      }
      
      .status-message.error {
        background: ${cssManager.bdTheme('hsl(0 72.2% 50.6% / 0.1)', 'hsl(0 72.2% 50.6% / 0.2)')};
        color: ${cssManager.bdTheme('hsl(0 72.2% 40.6%)', 'hsl(0 72.2% 60.6%)')};
      }
    `}
  </style>
  
  <div class="demo-container">
    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      const form = elementArg.querySelector('dees-form') as DeesForm;
      const outputDiv = elementArg.querySelector('.form-output');
      
      if (form && outputDiv) {
        form.addEventListener('formData', async (eventArg: CustomEvent) => {
          const data = eventArg.detail.data;
          console.log('Form submitted with data:', data);
          
          // Show processing state
          form.setStatus('pending', 'Processing your registration...');
          outputDiv.innerHTML = `<strong>Submitted Data:</strong>\n${JSON.stringify(data, null, 2)}`;
          
          // Simulate API call
          await domtools.plugins.smartdelay.delayFor(2000);
          
          // Show success
          form.setStatus('success', 'Registration completed successfully!');
          
          // Reset form after delay
          await domtools.plugins.smartdelay.delayFor(2000);
          form.reset();
          outputDiv.innerHTML = '<em>Form has been reset</em>';
        });
        
        // Track individual field changes
        const inputs = form.querySelectorAll('dees-input-text, dees-input-dropdown, dees-input-checkbox');
        inputs.forEach((input) => {
          input.addEventListener('changeSubject', () => {
            console.log('Field changed:', input.getAttribute('key'));
          });
        });
      }
    }}>
      <dees-panel .heading="Complete Form Example" .description="A comprehensive form with various input types, validation, and form submission handling">
        <dees-form>
          <dees-input-text 
            .required=${true} 
            key="firstName" 
            label="First Name"
            .description=${'Your given name'}
          ></dees-input-text>
          
          <dees-input-text 
            .required=${true} 
            key="lastName" 
            label="Last Name"
          ></dees-input-text>
          
          <dees-input-text 
            .required=${true} 
            key="email" 
            label="Email Address"
            .description=${'We will use this to contact you'}
          ></dees-input-text>
          
          <dees-input-dropdown
            .required=${true}
            key="country"
            .label=${'Country'}
            .options=${[
              { option: 'United States', key: 'us' },
              { option: 'Canada', key: 'ca' },
              { option: 'Germany', key: 'de' },
              { option: 'France', key: 'fr' },
              { option: 'United Kingdom', key: 'uk' },
            ]}
          ></dees-input-dropdown>
          
          <dees-input-text
            .required=${true}
            key="password"
            label="Password"
            isPasswordBool
            .description=${'Minimum 8 characters'}
          ></dees-input-text>
          
          <dees-input-checkbox
            .required=${true}
            key="terms"
            label="I agree to the Terms and Conditions"
          ></dees-input-checkbox>
          
          <dees-input-checkbox
            key="newsletter"
            label="Send me promotional emails"
            .value=${true}
          ></dees-input-checkbox>
          
          <dees-form-submit>Create Account</dees-form-submit>
        </dees-form>
        
        <div class="form-output">
          <em>Submit the form to see the collected data...</em>
        </div>
      </dees-panel>
    </dees-demowrapper>
    
    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      const form = elementArg.querySelector('dees-form') as DeesForm;
      
      if (form) {
        // Track horizontal layout behavior
        console.log('Horizontal form layout active');
        
        // Monitor filter changes
        form.addEventListener('formData', (event: CustomEvent) => {
          const filters = event.detail.data;
          console.log('Filter applied:', filters);
          
          // Simulate search
          const resultsCount = Math.floor(Math.random() * 100) + 1;
          console.log(`Found ${resultsCount} results with filters:`, filters);
        });
        
        // Setup real-time filter updates
        const inputs = form.querySelectorAll('[key]');
        inputs.forEach((input) => {
          input.addEventListener('changeSubject', async () => {
            // Get current form data
            const formData = await form.collectFormData();
            console.log('Live filter update:', formData);
          });
        });
      }
    }}>
      <dees-panel .heading="Horizontal Form Layout" .description="Compact form with inputs arranged horizontally - perfect for filters and quick forms">
        <dees-form horizontal-layout>
          <dees-input-text 
            key="search" 
            label="Search"
            placeholder="Enter keywords..."
          ></dees-input-text>
          
          <dees-input-dropdown
            key="category"
            .label=${'Category'}
            .enableSearch=${false}
            .options=${[
              { option: 'All', key: 'all' },
              { option: 'Products', key: 'products' },
              { option: 'Services', key: 'services' },
              { option: 'Support', key: 'support' },
            ]}
          ></dees-input-dropdown>
          
          <dees-input-dropdown
            key="sort"
            .label=${'Sort By'}
            .enableSearch=${false}
            .options=${[
              { option: 'Newest', key: 'newest' },
              { option: 'Popular', key: 'popular' },
              { option: 'Price: Low to High', key: 'price_asc' },
              { option: 'Price: High to Low', key: 'price_desc' },
            ]}
          ></dees-input-dropdown>
          
          <dees-input-checkbox
            key="inStock"
            label="In Stock Only"
            .value=${true}
          ></dees-input-checkbox>
        </dees-form>
      </dees-panel>
    </dees-demowrapper>
    
    <dees-demowrapper .runAfterRender=${async (elementArg: HTMLElement) => {
      const form = elementArg.querySelector('dees-form') as DeesForm;
      const statusDiv = elementArg.querySelector('#status-display');
      
      if (form) {
        form.addEventListener('formData', async (eventArg: CustomEvent) => {
          const data = eventArg.detail.data;
          console.log('Advanced form data:', data);
          
          // Show validation in progress
          form.setStatus('pending', 'Validating your information...');
          
          // Simulate validation
          await domtools.plugins.smartdelay.delayFor(1500);
          
          // Check IBAN validity (simple check)
          if (data.iban && data.iban.length > 15) {
            form.setStatus('success', 'Application submitted successfully!');
            
            if (statusDiv) {
              statusDiv.className = 'status-message success';
              statusDiv.textContent = '✓ Your application has been submitted. We will contact you soon.';
            }
          } else {
            form.setStatus('error', 'Please check your IBAN');
            
            if (statusDiv) {
              statusDiv.className = 'status-message error';
              statusDiv.textContent = '✗ Invalid IBAN format. Please check and try again.';
            }
          }
          
          console.log('Form data logged:', data);
        });
        
        // Monitor file uploads
        const fileUpload = form.querySelector('dees-input-fileupload');
        if (fileUpload) {
          fileUpload.addEventListener('change', (event: any) => {
            const files = event.detail?.files || [];
            console.log(`${files.length} file(s) selected for upload`);
          });
        }
      }
    }}>
      <dees-panel .heading="Advanced Form Features" .description="Form with specialized input types and complex validation">
        <dees-form>
          <dees-input-iban 
            key="iban"
            label="IBAN"
            .required=${true}
          ></dees-input-iban>
          
          <dees-input-phone
            key="phone"
            label="Phone Number"
            .required=${true}
          ></dees-input-phone>
          
          <dees-input-multitoggle
            key="preferences"
            .label=${'Notification Preferences'}
            .options=${['Email', 'SMS', 'Push', 'In-App']}
            .selectedOption=${'Email'}
          ></dees-input-multitoggle>
          
          <dees-input-multiselect
            key="interests"
            .label=${'Areas of Interest'}
            .options=${[
              { option: 'Technology', key: 'tech' },
              { option: 'Design', key: 'design' },
              { option: 'Business', key: 'business' },
              { option: 'Marketing', key: 'marketing' },
              { option: 'Sales', key: 'sales' },
            ]}
          ></dees-input-multiselect>
          
          <dees-input-fileupload
            key="documents"
            .label=${'Upload Documents'}
            .description=${'PDF, DOC, or DOCX files up to 10MB'}
          ></dees-input-fileupload>
          
          <dees-form-submit>Submit Application</dees-form-submit>
        </dees-form>
        
        <div id="status-display"></div>
      </dees-panel>
    </dees-demowrapper>
  </div>
`;