import React from 'react';
import { 
  FormSidebar, 
  FormField 
} from '@skybridge/web-components';
import { apiService, Application, CreateApplicationRequest } from '../services/apiService';

interface ApplicationSidebarProps {
  opened: boolean;
  onClose: () => void;
  onSuccess: () => void;
  editingApp?: Application | null;
}

const ApplicationSidebar: React.FC<ApplicationSidebarProps> = ({
  opened,
  onClose,
  onSuccess,
  editingApp,
}) => {
  const parseDuration = (duration: string): number => {
    // Convert duration string like "24h" to seconds
    const match = duration.match(/^(\d+)([hmd]?)$/);
    if (!match) return 86400; // Default to 24h in seconds
    
    const value = parseInt(match[1]);
    const unit = match[2] || 'h';
    
    switch (unit) {
      case 'm': return value * 60; // minutes to seconds
      case 'h': return value * 3600; // hours to seconds  
      case 'd': return value * 86400; // days to seconds
      default: return value * 3600; // default to hours
    }
  };

  const fields: FormField[] = [
    {
      name: 'app_id',
      label: 'Application ID',
      type: 'text',
      required: true,
      placeholder: 'my-app-id',
      disabled: !!editingApp, // Disable editing for existing apps
    },
    {
      name: 'app_link',
      label: 'Application Link',
      type: 'text',
      required: true,
      placeholder: 'https://myapp.example.com',
      validation: { url: true },
    },
    {
      name: 'type',
      label: 'Application Type',
      type: 'multiselect',
      required: true,
      options: [
        { value: 'static', label: 'Static Token App' },
        { value: 'user', label: 'User Token App' },
      ],
    },
    {
      name: 'callback_url',
      label: 'Callback URL',
      type: 'text',
      required: true,
      placeholder: 'https://myapp.example.com/callback',
      validation: { url: true },
    },
    {
      name: 'token_prefix',
      label: 'Token Prefix (Optional)',
      type: 'text',
      required: false,
      placeholder: 'myapp_',
    },
    {
      name: 'token_renewal_duration',
      label: 'Token Renewal Duration',
      type: 'text',
      required: false,
      placeholder: '24h',
      defaultValue: '24h',
    },
    {
      name: 'max_token_duration',
      label: 'Max Token Duration',
      type: 'text',
      required: false,
      placeholder: '168h',
      defaultValue: '168h',
    },
  ];

  const handleSubmit = async (values: any) => {
    const submitData = {
      ...values,
      token_renewal_duration_seconds: parseDuration(values.token_renewal_duration || '24h'),
      max_token_duration_seconds: parseDuration(values.max_token_duration || '168h'),
      owner: {
        type: 'individual',
        name: 'Admin User',
        owner: 'admin@example.com',
      },
    };

    if (editingApp) {
      await apiService.updateApplication(editingApp.app_id, submitData);
    } else {
      await apiService.createApplication(submitData);
    }
  };

  return (
    <FormSidebar
      opened={opened}
      onClose={onClose}
      onSuccess={onSuccess}
      title="Application"
      editMode={!!editingApp}
      editItem={editingApp}
      fields={fields}
      onSubmit={handleSubmit}
      width={450}
    />
  );
};

export default ApplicationSidebar;