export const FORM_TAB_THRESHOLD = 8
export const FORM_TAB_FIELD_LIMIT = 6

export type FormTab = {
  key: string
  label: string
  description?: string
  fields: string[]
}

export const resourceFormTabs: Record<string, FormTab[]> = {
  staff: [
    {
      key: 'profile',
      label: 'Profile',
      description: 'Basic staff identity, role, and contact details.',
      fields: [
        'photo_path',
        'first_name',
        'last_name',
        'email',
        'user_role',
        'position',
        'specialty',
        'license_number',
        'phone',
        'signature_path',
        'status',
        'send_login_access',
      ],
    },
    {
      key: 'address',
      label: 'Address',
      description: 'Mailing and location information.',
      fields: ['address_line_1', 'address_line_2', 'country', 'state_region', 'city'],
    },
    {
      key: 'availability',
      label: 'Availability',
      description: 'Weekly schedule and working hours.',
      fields: ['availability'],
    },
    {
      key: 'access',
      label: 'Access',
      description: 'Module permissions and assigned services.',
      fields: ['permissions', 'service_ids'],
    },
  ],
  branches: [
    {
      key: 'details',
      label: 'Branch Details',
      description: 'Name, code, and regulatory information.',
      fields: ['name', 'code', 'status', 'bir_tin'],
    },
    {
      key: 'location',
      label: 'Location',
      description: 'Address and map coordinates.',
      fields: ['address_line_1', 'address_line_2', 'country', 'state_region', 'city', 'google_map_url', 'latitude', 'longitude'],
    },
    {
      key: 'contact',
      label: 'Contact & Hours',
      description: 'Reachability and operating schedule.',
      fields: ['phone', 'email', 'emergency_info', 'business_hours'],
    },
  ],
  services: [
    {
      key: 'basic',
      label: 'Basic Info',
      description: 'Type, naming, and product imagery.',
      fields: ['type', 'status', 'name', 'sku', 'barcode', 'image_path', 'description'],
    },
    {
      key: 'pricing',
      label: 'Pricing & Inventory',
      description: 'Selling price, cost, and stock settings.',
      fields: ['price', 'cost_price', 'unit_of_measure', 'quantity_on_hand', 'track_inventory', 'reorder_level', 'duration_minutes'],
    },
    {
      key: 'assignments',
      label: 'Assignments',
      description: 'Staff and doctors linked to this item.',
      fields: ['staff_ids'],
    },
  ],
  customers: [
    {
      key: 'profile',
      label: 'Profile',
      description: 'Customer identity and account status.',
      fields: ['photo_path', 'customer_code', 'first_name', 'last_name', 'status'],
    },
    {
      key: 'contact',
      label: 'Contact & Address',
      description: 'Phone, email, and location details.',
      fields: ['address_line_1', 'address_line_2', 'country', 'state_region', 'city', 'phone', 'email', 'send_login_access'],
    },
  ],
  patients: [
    {
      key: 'profile',
      label: 'Profile',
      description: 'Demographics and identification.',
      fields: ['photo_path', 'customer_id', 'date_of_birth', 'age', 'gender', 'blood_type', 'first_name', 'last_name', 'status'],
    },
    {
      key: 'contact',
      label: 'Contact & Address',
      description: 'Phone, email, and location details.',
      fields: ['address_line_1', 'address_line_2', 'country', 'state_region', 'city', 'phone', 'email'],
    },
    {
      key: 'emergency',
      label: 'Emergency & Insurance',
      description: 'Emergency contacts and insurance coverage.',
      fields: ['emergency_contact_name', 'emergency_contact_relationship', 'emergency_contact_phone', 'insurance_provider', 'insurance_policy_number'],
    },
    {
      key: 'employment',
      label: 'Family & Employment',
      description: 'Family names and work-related details.',
      fields: ['mother_name', 'father_name', 'company_affiliated', 'job_position', 'job_industry'],
    },
  ],
  'widget-settings': [
    {
      key: 'branding',
      label: 'Branding',
      description: 'Colors, fonts, and introductory content.',
      fields: ['clinic_branch_id', 'widget_type_id', 'primary_color', 'header_footer_bg', 'header_footer_font_color', 'font_style', 'intro_content'],
    },
    {
      key: 'schedule',
      label: 'Schedule & Options',
      description: 'Booking window and patient self-service rules.',
      fields: ['time_range', 'expires_at', 'allow_reschedule', 'allow_cancel'],
    },
    {
      key: 'embed',
      label: 'Embed & Share',
      description: 'Public widget URL and iframe code.',
      fields: ['share_url', 'embed_html'],
    },
  ],
  'documentation-pages': [
    {
      key: 'content',
      label: 'Content',
      description: 'Title, slug, and page body.',
      fields: ['title', 'slug', 'content'],
    },
    {
      key: 'publish',
      label: 'Publishing',
      description: 'Visibility and publication status.',
      fields: ['status'],
    },
  ],
}

type FieldLike = { key: string }

export function resolveFormTabs(resource: string, fields: FieldLike[] = []): FormTab[] | null {
  const explicit = resourceFormTabs[resource]
  const visibleKeys = new Set(fields.map((field) => field.key))

  if (explicit?.length) {
    const tabs = explicit
      .map((tab) => ({
        ...tab,
        fields: tab.fields.filter((key) => visibleKeys.has(key)),
      }))
      .filter((tab) => tab.fields.length > 0)

    return tabs.length > 1 ? tabs : null
  }

  if (fields.length < FORM_TAB_THRESHOLD) return null

  const tabs: FormTab[] = []
  for (let index = 0; index < fields.length; index += FORM_TAB_FIELD_LIMIT) {
    const slice = fields.slice(index, index + FORM_TAB_FIELD_LIMIT)
    tabs.push({
      key: `section-${tabs.length + 1}`,
      label: tabs.length === 0 ? 'General' : `Section ${tabs.length + 1}`,
      fields: slice.map((field) => field.key),
    })
  }

  return tabs.length > 1 ? tabs : null
}

export function fieldsForTab<T extends FieldLike>(tabKey: string, tabs: FormTab[], fields: T[]): T[] {
  const tab = tabs.find((item) => item.key === tabKey)
  if (!tab) return fields

  const keys = new Set(tab.fields)
  return fields.filter((field) => keys.has(field.key))
}

export function formatLiveDateTime(date = new Date()) {
  return date.toLocaleString(undefined, {
    weekday: 'short',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
  })
}
