import React from 'react';
import { 
  Sidebar, 
  FormField,
  Stack,
  Group,
  Button,
  TextInput,
  Select,
  MultiSelect,
  useForm,
  notifications
} 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 form = useForm({
    initialValues: {
      app_id: editingApp?.app_id || '',
      app_link: editingApp?.app_link || '',
      type: editingApp?.type || [],
      callback_url: editingApp?.callback_url || '',
      token_prefix: editingApp?.token_prefix || '',
      token_renewal_duration: '24h',
      max_token_duration: '168h',
    },
    validate: {
      app_id: (value) => value.length < 1 ? 'Application ID is required' : null,
      app_link: (value) => value.length < 1 ? 'Application Link is required' : null,
      type: (value) => value.length < 1 ? 'Application Type is required' : null,
      callback_url: (value) => value.length < 1 ? 'Callback URL is required' : null,
    },
  });

  const parseDuration = (duration: string): number => {
    const match = duration.match(/^(\d+)([hmd]?)$/);
    if (!match) return 86400;
    
    const value = parseInt(match[1]);
    const unit = match[2] || 'h';
    
    switch (unit) {
      case 'm': return value * 60;
      case 'h': return value * 3600;
      case 'd': return value * 86400;
      default: return value * 3600;
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      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);
      }
      
      notifications.show({
        title: 'Success',
        message: `Application ${editingApp ? 'updated' : 'created'} successfully`,
        color: 'green',
      });
      
      onSuccess();
      onClose();
    } catch (error) {
      notifications.show({
        title: 'Error',
        message: `Failed to ${editingApp ? 'update' : 'create'} application`,
        color: 'red',
      });
    }
  };

  const footer = (
    <Group justify="flex-end" gap="sm">
      <Button variant="light" onClick={onClose}>
        Cancel
      </Button>
      <Button onClick={form.onSubmit(handleSubmit)}>
        {editingApp ? 'Update' : 'Create'} Application
      </Button>
    </Group>
  );

  return (
    <Sidebar
      opened={opened}
      onClose={onClose}
      title={editingApp ? 'Edit Application' : 'Create Application'}
      layoutMode={true}
      footer={footer}
    >
      <form onSubmit={form.onSubmit(handleSubmit)}>
        <Stack gap="md">
          <TextInput
            label="Application ID"
            placeholder="my-app-id"
            required
            disabled={!!editingApp}
            {...form.getInputProps('app_id')}
          />
          
          <TextInput
            label="Application Link"
            placeholder="https://myapp.example.com"
            required
            {...form.getInputProps('app_link')}
          />
          
          <MultiSelect
            label="Application Type"
            placeholder="Select application types"
            required
            data={[
              { value: 'static', label: 'Static Token App' },
              { value: 'user', label: 'User Token App' },
            ]}
            {...form.getInputProps('type')}
          />
          
          <TextInput
            label="Callback URL"
            placeholder="https://myapp.example.com/callback"
            required
            {...form.getInputProps('callback_url')}
          />
          
          <TextInput
            label="Token Prefix (Optional)"
            placeholder="myapp_"
            {...form.getInputProps('token_prefix')}
          />
          
          <TextInput
            label="Token Renewal Duration"
            placeholder="24h"
            {...form.getInputProps('token_renewal_duration')}
          />
          
          <TextInput
            label="Max Token Duration"
            placeholder="168h"
            {...form.getInputProps('max_token_duration')}
          />
        </Stack>
      </form>
    </Sidebar>
  );
};

export default ApplicationSidebar;