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

interface Props {
  data: ResumeData
}

export function ModernSidebar({ 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'

  // Dynamic photo inside the sidebar header
  const sidebarPhoto = () => {
    if (!data.photoUrl) return null
    const photoBorderRadius = {
      square: '0px',
      rounded: '12px',
      circle: '50%'
    }[settings.photoStyle] || '50%'

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

  return (
    <div
      className="print-page bg-white text-neutral-800"
      style={{
        width: '210mm',
        minHeight: '297mm',
        display: 'flex',
        fontSize: settings.fontSize,
        lineHeight: settings.lineHeight,
        ...fontStyle
      }}
    >
      <style dangerouslySetInnerHTML={{ __html: fontImport }} />

      {/* Left sidebar */}
      <div
        style={{
          width: '68mm',
          background: accent,
          color: '#ffffff',
          padding: `${settings.marginTB} 8mm ${settings.marginTB} 10mm`,
          flexShrink: 0,
          display: 'flex',
          flexDirection: 'column',
          gap: '24px'
        }}
      >
        {/* Profile Image & Name */}
        <div>
          {sidebarPhoto()}
          <h1
            style={{
              fontFamily: settings.fontFamily ? `"${settings.fontFamily}", sans-serif` : 'Space Grotesk, sans-serif',
              fontSize: nameSize,
              fontWeight: settings.nameBold ? 700 : 400,
              color: '#ffffff',
              lineHeight: 1.1,
              margin: 0
            }}
          >
            {data.fullName || 'Your Name'}
          </h1>
          {data.professionalTitle && (
            <p style={{ fontSize: '10.5pt', fontWeight: 600, color: 'rgba(255,255,255,0.9)', marginTop: '6px' }}>
              {data.professionalTitle}
            </p>
          )}
        </div>

        {/* Contact details with white icons */}
        <SidebarSection title="Contact">
          {data.email && (
            <SidebarItem
              label="Email"
              value={data.email}
              icon={renderIcon('email', settings, accent, true)}
            />
          )}
          {data.phone && (
            <SidebarItem
              label="Phone"
              value={data.phone}
              icon={renderIcon('phone', settings, accent, true)}
            />
          )}
          {data.location && (
            <SidebarItem
              label="Location"
              value={data.location}
              icon={renderIcon('location', settings, accent, true)}
            />
          )}
        </SidebarSection>

        {/* Skills */}
        {data.skills.length > 0 && (
          <SidebarSection title="Skills">
            {data.skills.map((skill, i) => (
              <div key={i} style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '8.5pt' }}>
                  <span>{skill.name}</span>
                  {skill.level && <span style={{ opacity: 0.75 }}>{skill.level}</span>}
                </div>
                <div style={{ height: '3px', background: 'rgba(255,255,255,0.2)', borderRadius: '2px', marginTop: '3px' }}>
                  <div
                    style={{
                      height: '3px',
                      borderRadius: '2px',
                      background: 'rgba(255,255,255,0.9)',
                      width:
                        skill.level === 'Expert'
                          ? '100%'
                          : skill.level === 'Advanced'
                          ? '80%'
                          : skill.level === 'Intermediate'
                          ? '60%'
                          : '40%'
                    }}
                  />
                </div>
              </div>
            ))}
          </SidebarSection>
        )}
      </div>

      {/* Main content */}
      <div
        style={{
          flex: 1,
          padding: `${settings.marginTB} ${settings.marginLR}`,
          display: 'flex',
          flexDirection: 'column',
          overflow: 'hidden'
        }}
      >
        <div style={{ flexGrow: 1, display: 'flex', flexDirection: 'column', gap: '20px' }}>
          {/* Summary */}
          {data.summary && (
            <MainSection title="About Me" accent={accent} settings={settings}>
              <p style={{ color: '#52525b', margin: 0, whiteSpace: 'pre-line' }}>{data.summary}</p>
            </MainSection>
          )}

          {/* Experience */}
          {data.experiences.length > 0 && (
            <MainSection title="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' : '10px',
                    borderLeft: `2px solid ${accent}20`
                  }}
                >
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', flexWrap: 'wrap', gap: '4px' }}>
                    <strong style={{ ...subStyle, color: '#18181b' }}>{exp.jobTitle}</strong>
                    <span style={{ fontSize: '8pt', color: '#71717a' }}>
                      {exp.startDate} – {exp.current ? 'Present' : exp.endDate}
                    </span>
                  </div>
                  <div style={{ color: accent, fontSize: '9pt', fontWeight: 600 }}>
                    {exp.company}{exp.location ? ` · ${exp.location}` : ''}
                  </div>
                  {exp.description && (
                    <p
                      style={{
                        marginTop: '4px',
                        color: '#52525b',
                        fontSize: '8.5pt',
                        listStyleType: listStyleType,
                        paddingLeft: settings.listStyle === 'bullet' ? '12px' : 0
                      }}
                    >
                      {exp.description}
                    </p>
                  )}
                </div>
              ))}
            </MainSection>
          )}

          {/* Education */}
          {data.education.length > 0 && (
            <MainSection 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', gap: '4px' }}>
                    <strong style={{ ...subStyle, color: '#18181b' }}>{edu.degree}</strong>
                    <span style={{ fontSize: '8pt', color: '#71717a' }}>
                      {edu.startDate} – {edu.endDate}
                    </span>
                  </div>
                  <div style={{ color: accent, fontSize: '9pt', fontWeight: 600 }}>
                    {edu.institution}{edu.location ? ` · ${edu.location}` : ''}
                  </div>
                  {edu.description && <p style={{ marginTop: '3px', color: '#52525b', fontSize: '8.5pt' }}>{edu.description}</p>}
                </div>
              ))}
            </MainSection>
          )}

          {/* Projects */}
          {data.projects.length > 0 && (
            <MainSection title="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 style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <strong style={{ ...subStyle, color: '#18181b' }}>{proj.name}</strong>
                    {proj.url && renderLink(proj.url, settings, accent)}
                  </div>
                  {proj.description && <p style={{ marginTop: '3px', color: '#52525b', fontSize: '8.5pt' }}>{proj.description}</p>}
                </div>
              ))}
            </MainSection>
          )}
        </div>

        {renderFooter(data, settings)}
      </div>
    </div>
  )
}

function SidebarSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div style={{ marginBottom: '20px' }}>
      <h2
        style={{
          fontFamily: 'Space Grotesk, sans-serif',
          fontSize: '8pt',
          fontWeight: 700,
          textTransform: 'uppercase',
          letterSpacing: '0.1em',
          color: 'rgba(255,255,255,0.7)',
          marginBottom: '8px',
          borderBottom: '1px solid rgba(255,255,255,0.2)',
          paddingBottom: '4px'
        }}
      >
        {title}
      </h2>
      {children}
    </div>
  )
}

interface SidebarItemProps {
  label: string
  value: string
  icon?: React.ReactNode
}

function SidebarItem({ label, value, icon }: SidebarItemProps) {
  return (
    <div style={{ marginBottom: '8px', fontSize: '8.5pt' }}>
      <div style={{ color: 'rgba(255,255,255,0.7)', fontSize: '7.5pt', textTransform: 'uppercase', letterSpacing: '0.06em', display: 'flex', alignItems: 'center', gap: '4px' }}>
        {icon}
        <span>{label}</span>
      </div>
      <div style={{ color: '#ffffff', wordBreak: 'break-all', marginTop: '2px', paddingLeft: icon ? '22px' : 0 }}>{value}</div>
    </div>
  )
}

function MainSection({ 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,
          color: accent,
          borderBottom: `1.5px solid ${accent}15`,
          paddingBottom: '4px',
          marginBottom: '10px'
        }}
      >
        {title}
      </h2>
      {children}
    </div>
  )
}
