import axios from 'axios';

type InventoryImportEntity = 'properties' | 'unit_types' | 'units';

type InventoryTemplateExample = {
  column: string;
  value: string;
  note?: string;
};

export type InventoryTemplateConfig = {
  columns: string[];
  requiredColumns: string[];
  fileName: string;
  workflowHint: string;
  referenceHint: string;
  exampleReferences: InventoryTemplateExample[];
  exampleRow: InventoryTemplateExample[];
};

const triggerBlobDownload = (blob: Blob, fileName: string) => {
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
  window.URL.revokeObjectURL(link.href);
};

const getFileNameFromHeaders = (contentDisposition?: string) => {
  const match = contentDisposition?.match(/filename="?([^";]+)"?/i);
  return match?.[1] || null;
};

export const downloadInventoryImportTemplate = async (
  entity: InventoryImportEntity,
  fallbackFileName: string,
) => {
  const response = await axios({
    url: `/${entity}/import-template`,
    method: 'GET',
    responseType: 'blob',
  });

  const fileName = getFileNameFromHeaders(response.headers['content-disposition']) || fallbackFileName;
  const type = response.headers['content-type'] || 'text/csv';
  const blob = new Blob([response.data], { type });

  triggerBlobDownload(blob, fileName);
};

export const getInventoryImportTemplateConfig = (
  entity: InventoryImportEntity,
  currentUser: any,
): InventoryTemplateConfig => {
  const globalAccess = Boolean(currentUser?.app_role?.globalAccess);

  switch (entity) {
    case 'properties':
      return {
        columns: globalAccess
          ? ['tenant', 'organization', 'name', 'code', 'address', 'city', 'country', 'timezone', 'description', 'is_active']
          : ['name', 'code', 'address', 'city', 'country', 'timezone', 'description', 'is_active'],
        requiredColumns: globalAccess ? ['organization'] : [],
        fileName: 'properties-import-template.csv',
        workflowHint: globalAccess
          ? 'Use tenant and organization only when you are setting up customer workspaces as a global admin.'
          : 'Tenant and organization are assigned automatically from your current workspace, so they are not part of this template.',
        referenceHint: globalAccess
          ? 'Tenant accepts an existing tenant ID, slug, or name. Organization accepts an existing organization ID or name within that tenant.'
          : 'Each row creates one property inside your current workspace.',
        exampleReferences: globalAccess
          ? [
              {
                column: 'tenant',
                value: 'acme',
                note: 'Example slug. You can also use the tenant UUID or tenant name.',
              },
              {
                column: 'organization',
                value: 'Acme Hospitality',
                note: 'Use an existing organization ID or organization name inside the selected tenant.',
              },
            ]
          : [],
        exampleRow: globalAccess
          ? [
              { column: 'tenant', value: 'acme' },
              { column: 'organization', value: 'Acme Hospitality' },
              { column: 'name', value: 'Sunset Suites' },
              { column: 'code', value: 'SUNSET-SF' },
              { column: 'address', value: '100 Market St' },
              { column: 'city', value: 'San Francisco' },
              { column: 'country', value: 'USA' },
              { column: 'timezone', value: 'America/Los_Angeles' },
              { column: 'description', value: 'Downtown furnished stay' },
              { column: 'is_active', value: 'true' },
            ]
          : [
              { column: 'name', value: 'Sunset Suites' },
              { column: 'code', value: 'SUNSET-SF' },
              { column: 'address', value: '100 Market St' },
              { column: 'city', value: 'San Francisco' },
              { column: 'country', value: 'USA' },
              { column: 'timezone', value: 'America/Los_Angeles' },
              { column: 'description', value: 'Downtown furnished stay' },
              { column: 'is_active', value: 'true' },
            ],
      };
    case 'unit_types':
      return {
        columns: [
          'property',
          'name',
          'code',
          'description',
          'max_occupancy',
          'bedrooms',
          'bathrooms',
          'minimum_stay_nights',
          'size_sqm',
          'base_nightly_rate',
          'base_monthly_rate',
        ],
        requiredColumns: ['property'],
        fileName: 'unit-types-import-template.csv',
        workflowHint: 'Import unit types only after the property already exists.',
        referenceHint: 'The property column can use an existing property ID, code, or name from your workspace.',
        exampleReferences: [
          {
            column: 'property',
            value: 'SUNSET-SF',
            note: 'Example property code. You can also use the property UUID or property name.',
          },
        ],
        exampleRow: [
          { column: 'property', value: 'SUNSET-SF' },
          { column: 'name', value: 'Studio Deluxe' },
          { column: 'code', value: 'STD-DELUXE' },
          { column: 'description', value: 'Large studio with kitchenette' },
          { column: 'max_occupancy', value: '2' },
          { column: 'bedrooms', value: '0' },
          { column: 'bathrooms', value: '1' },
          { column: 'minimum_stay_nights', value: '2' },
          { column: 'size_sqm', value: '38' },
          { column: 'base_nightly_rate', value: '189.00' },
          { column: 'base_monthly_rate', value: '4200.00' },
        ],
      };
    case 'units':
      return {
        columns: ['property', 'unit_type', 'unit_number', 'floor', 'status', 'max_occupancy_override', 'notes'],
        requiredColumns: ['property', 'unit_type'],
        fileName: 'units-import-template.csv',
        workflowHint: 'Import units only after both the property and the unit type already exist.',
        referenceHint: 'The property column can use a property ID, code, or name. The unit_type column can use a unit type ID, code, or name within that property.',
        exampleReferences: [
          {
            column: 'property',
            value: 'SUNSET-SF',
            note: 'Example property code. You can also use the property UUID or property name.',
          },
          {
            column: 'unit_type',
            value: 'STD-DELUXE',
            note: 'Example unit type code within that property. You can also use the unit type UUID or unit type name.',
          },
          {
            column: 'status',
            value: 'available',
            note: 'Valid statuses: available, occupied, maintenance, cleaning_hold, reserved, out_of_service.',
          },
        ],
        exampleRow: [
          { column: 'property', value: 'SUNSET-SF' },
          { column: 'unit_type', value: 'STD-DELUXE' },
          { column: 'unit_number', value: '405' },
          { column: 'floor', value: '4' },
          { column: 'status', value: 'available' },
          { column: 'max_occupancy_override', value: '2' },
          { column: 'notes', value: 'Corner unit with city view' },
        ],
      };
    default:
      throw new Error(`Unknown inventory import entity: ${entity}`);
  }
};
