// src/components/resume/templates/MotifCustom.tsx
import React from 'react'
import type { ResumeData } from '@/types'
import {
  parseDesignSettings,
  getFontImportsAndStyle,
  getNameSize,
  getSubtitleStyle,
  renderContactDetails,
  renderPhoto,
  renderFooter,
  renderLink
} from './templateHelper'

interface Props {
  data: ResumeData
}

export function MotifCustom({ data }: Props) {
  const settings = parseDesignSettings(data)
  const accent = data.accentColor || '#5563f5'
  const { fontImport, fontStyle } = getFontImportsAndStyle(settings)
  const nameSize = getNameSize(settings)
  const subStyle = getSubtitleStyle(settings, accent)

  const listStyleType = settings.listStyle === 'bullet' ? 'disc' : 'none'

  const renderPersonalHeader = () => {
    const isHeaderLeft = settings.headerPosition === 'left'
    const isHeaderRight = settings.headerPosition === 'right'
    const headerAlign = settings.photoAlignment === 'center' ? 'center' : 'left'

    return (
      <div style={{
        display: 'flex',
        flexDirection: isHeaderLeft ? 'row' : isHeaderRight ? 'row-reverse' : 'column',
        alignItems: 'center',
        justifyContent: 'space-between',
        borderBottom: `2.5px solid ${accent}`,
        paddingBottom: '16px',
        marginBottom: '20px',
        textAlign: isHeaderLeft ? 'left' : isHeaderRight ? 'right' : (headerAlign as any)
      }}>
        <div style={{ flex: 1 }}>
          {renderPhoto(data, settings, accent)}
          <h1 style={{
            fontFamily: settings.fontFamily ? `"${settings.fontFamily}", sans-serif` : 'Space Grotesk, sans-serif',
            fontSize: nameSize,
            fontWeight: settings.nameBold ? 700 : 400,
            color: '#111827',
            letterSpacing: '-0.02em',
            margin: 0,
            lineHeight: 1.1
          }}>
            {data.fullName || 'Your Name'}
          </h1>
          
          {data.professionalTitle && (
            <p style={{
              fontSize: '12pt',
              fontWeight: 600,
              color: accent,
              marginTop: '6px',
              marginBottom: '8px',
              letterSpacing: '0.02em'
            }}>
              {data.professionalTitle}
            </p>
          )}

          <div style={{
            display: 'flex',
            flexWrap: 'wrap',
            justifyContent: isHeaderLeft ? 'flex-start' : isHeaderRight ? 'flex-end' : (headerAlign === 'center' ? 'center' : 'flex-start'),
            gap: settings.detailsArrangement === 'icon' ? '12px' : '4px',
            alignItems: 'center',
            marginTop: '8px',
            fontSize: '9.5pt',
            color: '#4b5563'
          }}>
            {renderContactDetails(data, settings, accent, false)}
          </div>
        </div>
      </div>
    )
  }

  const leftColWidth = `${settings.columnWidthLeft}%`
  const rightColWidth = `${settings.columnWidthRight}%`

  const resumeBody = () => {
    const renderSections = (cols: 'left' | 'right' | 'all') => {
      const showExp = cols === 'all' || (settings.columns === 'two' ? cols === 'right' : true)
      const showEdu = cols === 'all' || (settings.columns === 'two' ? cols === 'left' : true)
      const showSkills = cols === 'all' || (settings.columns === 'two' ? cols === 'left' : true)
      const showProjects = cols === 'all' || (settings.columns === 'two' ? cols === 'right' : true)

      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
          {/* Summary */}
          {data.summary && cols !== 'left' && (
            <Section title="Profile Summary" accent={accent} settings={settings}>
              <p style={{ color: '#374151', margin: 0, whiteSpace: 'pre-line' }}>{data.summary}</p>
            </Section>
          )}

          {/* Skills */}
          {data.skills.length > 0 && showSkills && (
            <Section title="Skills" accent={accent} settings={settings}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                {data.skills.map((skill, i) => (
                  <span key={i} style={{ background: '#f3f4f6', border: `1px solid #e5e7eb`, borderRadius: '6px', padding: '3px 9px', fontSize: '8.5pt', color: '#1f2937', fontWeight: 500 }}>
                    {skill.name}{skill.level ? ` · ${skill.level}` : ''}
                  </span>
                ))}
              </div>
            </Section>
          )}

          {/* Experience */}
          {data.experiences.length > 0 && showExp && (
            <Section title="Professional Experience" accent={accent} settings={settings}>
              {data.experiences.map((exp, i) => (
                <div key={i} style={{ marginBottom: i < data.experiences.length - 1 ? settings.entrySpacing : 0, paddingLeft: settings.indentBody ? '12px' : 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap' }}>
                    <strong style={{ ...subStyle, color: '#111827' }}>{exp.jobTitle}</strong>
                    <span style={{ fontSize: '8.5pt', color: '#6b7280', fontWeight: 500 }}>
                      {exp.startDate} – {exp.current ? 'Present' : exp.endDate || ''}
                    </span>
                  </div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', color: accent, fontSize: '9pt', fontWeight: 600, marginTop: '2px' }}>
                    <span>{exp.company}{exp.location ? `, ${exp.location}` : ''}</span>
                  </div>
                  {exp.description && (
                    <p style={{
                      marginTop: '6px',
                      color: '#4b5563',
                      fontSize: '9pt',
                      lineHeight: settings.lineHeight,
                      listStyleType: listStyleType,
                      paddingLeft: settings.listStyle === 'bullet' ? '12px' : 0
                    }}>
                      {exp.description}
                    </p>
                  )}
                </div>
              ))}
            </Section>
          )}

          {/* Education */}
          {data.education.length > 0 && showEdu && (
            <Section title="Education" accent={accent} settings={settings}>
              {data.education.map((edu, i) => (
                <div key={i} style={{ marginBottom: i < data.education.length - 1 ? settings.entrySpacing : 0, paddingLeft: settings.indentBody ? '12px' : 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap' }}>
                    <strong style={{ ...subStyle, color: '#111827' }}>{edu.degree}</strong>
                    <span style={{ fontSize: '8.5pt', color: '#6b7280', fontWeight: 500 }}>
                      {edu.startDate} – {edu.endDate || ''}
                    </span>
                  </div>
                  <div style={{ color: accent, fontSize: '9pt', fontWeight: 600, marginTop: '2px' }}>
                    {edu.institution}{edu.location ? `, ${edu.location}` : ''}
                  </div>
                  {edu.description && <p style={{ marginTop: '4px', color: '#4b5563', fontSize: '9pt' }}>{edu.description}</p>}
                </div>
              ))}
            </Section>
          )}

          {/* Projects */}
          {data.projects.length > 0 && showProjects && (
            <Section title="Key Projects" accent={accent} settings={settings}>
              {data.projects.map((proj, i) => (
                <div key={i} style={{ marginBottom: i < data.projects.length - 1 ? settings.entrySpacing : 0, paddingLeft: settings.indentBody ? '12px' : 0 }}>
                  <div className="flex items-baseline justify-between flex-wrap">
                    <strong style={{ ...subStyle, color: '#111827' }}>{proj.name}</strong>
                    {proj.url && renderLink(proj.url, settings, accent)}
                  </div>
                  {proj.description && <p style={{ marginTop: '4px', color: '#4b5563', fontSize: '9pt', lineHeight: settings.lineHeight }}>{proj.description}</p>}
                </div>
              ))}
            </Section>
          )}
        </div>
      )
    }

    if (settings.columns === 'two') {
      return (
        <div style={{ display: 'flex', gap: '24px' }}>
          <div style={{ width: leftColWidth, display: 'flex', flexDirection: 'column', gap: '20px' }}>
            {renderSections('left')}
          </div>
          <div style={{ width: rightColWidth, display: 'flex', flexDirection: 'column', gap: '20px' }}>
            {renderSections('right')}
          </div>
        </div>
      )
    }

    return renderSections('all')
  }

  return (
    <div
      className="print-page bg-white text-neutral-800"
      style={{
        width: '210mm',
        minHeight: '297mm',
        padding: `${settings.marginTB} ${settings.marginLR}`,
        fontSize: settings.fontSize,
        lineHeight: settings.lineHeight,
        display: 'flex',
        flexDirection: 'column',
        ...fontStyle
      }}
    >
      <style dangerouslySetInnerHTML={{ __html: fontImport }} />
      {renderPersonalHeader()}
      <div style={{ flexGrow: 1 }}>
        {resumeBody()}
      </div>
      {renderFooter(data, settings)}
    </div>
  )
}

function Section({ title, accent, settings, children }: { title: string; accent: string; settings: any; children: React.ReactNode }) {
  return (
    <div style={{ marginBottom: '14px' }}>
      <h2 style={{
        fontFamily: settings.fontFamily ? `"${settings.fontFamily}", sans-serif` : 'Space Grotesk, sans-serif',
        fontSize: '11pt',
        fontWeight: 700,
        textTransform: 'uppercase',
        letterSpacing: '0.05em',
        color: accent,
        borderBottom: `1.5px solid ${accent}44`,
        paddingBottom: '4px',
        marginBottom: '10px',
      }}>
        {title}
      </h2>
      {children}
    </div>
  )
}
