// src/components/resume/templates/templateHelper.tsx
import React from 'react'
import type { ResumeData } from '@/types'

export interface DesignSettings {
  fontSize: string
  lineHeight: string
  marginLR: string
  marginTB: string
  entrySpacing: string
  columns: 'one' | 'two'
  headerPosition: 'top' | 'left' | 'right'
  columnWidthLeft: number
  columnWidthRight: number
  titleSubtitleSize: 'S' | 'M' | 'L'
  subtitleStyle: 'Normal' | 'Bold' | 'Italic'
  subtitlePlacement: 'sameLine' | 'nextLine'
  indentBody: boolean
  listStyle: 'bullet' | 'hyphen'
  footerPageNumbers: boolean
  footerEmail: boolean
  footerName: boolean
  fontType: string
  fontFamily: string
  linkUnderline: boolean
  linkBlueColor: boolean
  linkIcon: boolean
  detailsArrangement: 'bullet' | 'pipe' | 'bar' | 'icon'
  iconStyle: 'none' | 'circleFilled' | 'roundedFilled' | 'squareFilled' | 'circleOutline' | 'roundedOutline' | 'squareOutline'
  nameSize: 'xs' | 's' | 'm' | 'l' | 'xl'
  nameBold: boolean
  photoStyle: 'square' | 'rounded' | 'circle'
  photoSize: number
  photoBorder: boolean
  photoAlignment: 'left' | 'center' | 'right'
}

export const defaultSettings: DesignSettings = {
  fontSize: '10pt',
  lineHeight: '1.4',
  marginLR: '18mm',
  marginTB: '16mm',
  entrySpacing: '14px',
  columns: 'one',
  headerPosition: 'top',
  columnWidthLeft: 40,
  columnWidthRight: 60,
  titleSubtitleSize: 'M',
  subtitleStyle: 'Bold',
  subtitlePlacement: 'nextLine',
  indentBody: false,
  listStyle: 'bullet',
  footerPageNumbers: false,
  footerEmail: false,
  footerName: false,
  fontType: 'sans',
  fontFamily: 'Montserrat',
  linkUnderline: true,
  linkBlueColor: true,
  linkIcon: true,
  detailsArrangement: 'bullet',
  iconStyle: 'none',
  nameSize: 'l',
  nameBold: true,
  photoStyle: 'circle',
  photoSize: 90,
  photoBorder: true,
  photoAlignment: 'left'
}

export function parseDesignSettings(data: ResumeData): DesignSettings {
  let settings = { ...defaultSettings }
  if (data.designSettings) {
    try {
      const parsed = JSON.parse(data.designSettings)
      settings = { ...settings, ...parsed }
    } catch (e) {
      console.error('Failed to parse design settings', e)
    }
  }
  return settings
}

export function getFontImportsAndStyle(settings: DesignSettings) {
  const fontImport = settings.fontFamily
    ? `@import url('https://fonts.googleapis.com/css2?family=${settings.fontFamily.replace(/\s+/g, '+')}:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&display=swap');`
    : ''

  const fontStyle = {
    fontFamily: settings.fontFamily ? `"${settings.fontFamily}", sans-serif` : 'Montserrat, sans-serif'
  }

  return { fontImport, fontStyle }
}

export function getNameSize(settings: DesignSettings): string {
  const nameSizes = {
    xs: '18pt',
    s: '22pt',
    m: '26pt',
    l: '32pt',
    xl: '40pt'
  }
  return nameSizes[settings.nameSize] || '26pt'
}

export function getSubtitleStyle(settings: DesignSettings, accentColor: string): React.CSSProperties {
  const subtitleSizes = {
    S: '9pt',
    M: '10.5pt',
    L: '12pt'
  }
  const subSize = subtitleSizes[settings.titleSubtitleSize] || '10.5pt'
  return {
    fontSize: subSize,
    fontWeight: settings.subtitleStyle === 'Bold' ? 700 : 500,
    fontStyle: settings.subtitleStyle === 'Italic' ? 'italic' : 'normal',
  }
}

export function renderIcon(type: 'email' | 'phone' | 'location', settings: DesignSettings, accentColor: string, forceWhite: boolean = false) {
  const getIconSvg = () => {
    if (type === 'email') {
      return <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" />
    }
    if (type === 'phone') {
      return <path d="M6.62 10.79a15.149 15.149 0 0 0 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z" />
    }
    return <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" />
  }

  const iconColor = forceWhite ? '#ffffff' : accentColor

  const baseStyle: React.CSSProperties = {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '18px',
    height: '18px',
    marginRight: '4px',
    verticalAlign: 'middle',
  }

  // If forceWhite is active, filled frames should have white background and accent text, or vice versa, but white/black contrast is key.
  // Standard filled circle/rounded: Background is iconColor, SVG fill is white or contrast color.
  const svgFill = (settings.iconStyle.endsWith('Filled') && forceWhite) ? accentColor : (settings.iconStyle.endsWith('Filled') ? '#ffffff' : 'currentColor')
  const frameBg = forceWhite ? '#ffffff' : accentColor

  if (settings.iconStyle === 'circleFilled') {
    return (
      <span style={{ ...baseStyle, background: frameBg, color: svgFill, borderRadius: '50%' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }
  if (settings.iconStyle === 'roundedFilled') {
    return (
      <span style={{ ...baseStyle, background: frameBg, color: svgFill, borderRadius: '4px' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }
  if (settings.iconStyle === 'squareFilled') {
    return (
      <span style={{ ...baseStyle, background: frameBg, color: svgFill, borderRadius: '0px' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }
  if (settings.iconStyle === 'circleOutline') {
    return (
      <span style={{ ...baseStyle, border: `1px solid ${iconColor}`, color: iconColor, borderRadius: '50%' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }
  if (settings.iconStyle === 'roundedOutline') {
    return (
      <span style={{ ...baseStyle, border: `1px solid ${iconColor}`, color: iconColor, borderRadius: '4px' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }
  if (settings.iconStyle === 'squareOutline') {
    return (
      <span style={{ ...baseStyle, border: `1px solid ${iconColor}`, color: iconColor, borderRadius: '0px' }}>
        <svg style={{ width: '10px', height: '10px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
      </span>
    )
  }

  return (
    <span style={{ ...baseStyle, color: iconColor }}>
      <svg style={{ width: '14px', height: '14px', fill: 'currentColor' }} viewBox="0 0 24 24">{getIconSvg()}</svg>
    </span>
  )
}

export function renderLink(url: string, settings: DesignSettings, accentColor: string) {
  if (!url) return null
  const text = url.replace(/^(https?:\/\/)?(www\.)?/, '')
  const linkColor = settings.linkBlueColor ? '#2563eb' : accentColor
  return (
    <a
      href={url}
      target="_blank"
      rel="noopener noreferrer"
      style={{
        color: linkColor,
        textDecoration: settings.linkUnderline ? 'underline' : 'none',
        display: 'inline-flex',
        alignItems: 'center',
        gap: '3px',
        fontWeight: 500
      }}
    >
      {settings.linkIcon && (
        <svg style={{ width: '12px', height: '12px', fill: 'currentColor' }} viewBox="0 0 24 24">
          <path d="M10 6v2H5v11h11v-5h2v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h6zm11-3v8h-2V6.414l-8.293 8.293-1.414-1.414L17.586 5H13V3h8z"/>
        </svg>
      )}
      <span>{text}</span>
    </a>
  )
}

export function renderContactDetails(data: ResumeData, settings: DesignSettings, accentColor: string, forceWhiteIcons: boolean = false) {
  const separator = {
    bullet: ' • ',
    pipe: ' | ',
    bar: ' / ',
    icon: '   '
  }[settings.detailsArrangement] || ' • '

  const items = [
    { key: 'email', val: data.email, type: 'email' as const },
    { key: 'phone', val: data.phone, type: 'phone' as const },
    { key: 'location', val: data.location, type: 'location' as const }
  ].filter(i => !!i.val)

  if (items.length === 0) return null

  if (settings.detailsArrangement === 'icon') {
    return (
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: '12px', alignItems: 'center' }}>
        {items.map((item, idx) => (
          <span key={item.key} style={{ display: 'inline-flex', alignItems: 'center' }}>
            {renderIcon(item.type, settings, accentColor, forceWhiteIcons)}
            <span>{item.val}</span>
          </span>
        ))}
      </div>
    )
  }

  // Text layout with separators
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', alignItems: 'center' }}>
      {items.map((item, idx) => (
        <React.Fragment key={item.key}>
          <span style={{ display: 'inline-flex', alignItems: 'center' }}>
            <span>{item.val}</span>
          </span>
          {idx < items.length - 1 && <span style={{ color: forceWhiteIcons ? 'rgba(255,255,255,0.4)' : '#d1d5db' }}>{separator}</span>}
        </React.Fragment>
      ))}
    </div>
  )
}

export function renderPhoto(data: ResumeData, settings: DesignSettings, accentColor: string) {
  if (!data.photoUrl) return null

  const photoBorderRadius = {
    square: '0px',
    rounded: '12px',
    circle: '50%'
  }[settings.photoStyle] || '50%'

  return (
    <div style={{ display: 'flex', justifyContent: settings.photoAlignment === 'center' ? 'center' : settings.photoAlignment === 'right' ? 'flex-end' : 'flex-start', marginBottom: '14px' }}>
      <img
        src={data.photoUrl}
        alt={data.fullName}
        style={{
          width: `${settings.photoSize}px`,
          height: `${settings.photoSize}px`,
          objectFit: 'cover',
          borderRadius: photoBorderRadius,
          border: settings.photoBorder ? `3px solid ${accentColor}` : 'none',
          boxShadow: '0 4px 6px -1px rgb(0 0 0 / 0.1)'
        }}
      />
    </div>
  )
}

export function renderFooter(data: ResumeData, settings: DesignSettings) {
  if (!settings.footerName && !settings.footerEmail && !settings.footerPageNumbers) return null
  return (
    <div style={{
      marginTop: 'auto',
      paddingTop: '20px',
      borderTop: '1px solid #e5e7eb',
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      fontSize: '8pt',
      color: '#9ca3af'
    }}>
      <div>
        {settings.footerName && <span style={{ marginRight: '12px' }}>{data.fullName}</span>}
        {settings.footerEmail && <span>{data.email}</span>}
      </div>
      {settings.footerPageNumbers && <span>Page 1 of 1</span>}
    </div>
  )
}
