'use client'

import { motion } from 'framer-motion'
import { useState, useEffect } from 'react'
import { GitBranch, CheckCircle, XCircle, Loader2 } from 'lucide-react'
import { useLanguage } from '@/lib/LanguageContext'

interface RepoCI {
  sha: string
  status: string
  url: string
}

function CIBadge({ repo, forgejoUrl }: { repo: string; forgejoUrl: string }) {
  const [ci, setCI] = useState<RepoCI | null>(null)

  useEffect(() => {
    fetch(`/api/ci-status?repo=${repo}`)
      .then(r => r.json())
      .then(data => setCI({
        sha: data.sha?.substring(0, 7) || '',
        status: data.conclusion || data.status || 'unknown',
        url: data.url || `${forgejoUrl}/actions`,
      }))
      .catch(() => null)
  }, [repo, forgejoUrl])

  if (!ci || !ci.sha) return null

  const icon = ci.status === 'success'
    ? <CheckCircle size={12} className="text-green-500" />
    : ci.status === 'failure'
      ? <XCircle size={12} className="text-red-500" />
      : <Loader2 size={12} className="animate-spin text-yellow-500" />

  return (
    <a
      href={`${forgejoUrl}/commit/${ci.sha}`}
      target="_blank"
      rel="noopener noreferrer"
      className="flex items-center gap-1.5 px-2 py-1 rounded-full bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 hover:border-blue-400 dark:hover:border-blue-600 transition-colors"
    >
      <GitBranch size={10} className="text-gray-400" />
      <span className="text-xs font-mono text-gray-600 dark:text-gray-300">{ci.sha}</span>
      {icon}
    </a>
  )
}

const colors = [
  'from-green-500 to-green-600',
  'from-red-500 to-red-600',
  'from-orange-500 to-orange-600',
  'from-cyan-500 to-cyan-600',
  'from-blue-500 to-blue-600',
]

const skills = [
  ['Kubernetes', 'Talos', 'ArgoCD', 'Terraform', 'Authentik', 'Prometheus', 'Grafana', 'vLLM', 'Temporal', 'Kafka', 'PostgreSQL', 'Go'],
  ['Golang', 'Terraform', 'IaC', 'OpenShift', 'Docker', 'Distributed Systems', 'Grafana'],
  ['Java', 'AWS', 'DynamoDB', 'CloudWatch', 'gRPC', 'Distributed Systems', 'Ownership', 'Disaster Recovery', 'Observability'],
  ['C++', 'CMake', 'Golang', 'Docker'],
  ['ReactJS', 'Django', 'Agile', 'Sonar'],
]

const links = [
  '#project-homelab', // Homelab - link to homelab project showcase
  '#project-rbc', // RBC - link to RBC project showcase
  '#project-aws', // AWS - link to AWS project showcase
  null,
  'https://plan.navcanada.ca/account/login/?next=/',
]

const linkTexts = [
  'Learn more →',
  'Learn more →',
  'Learn more →',
  '',
  'View Product →',
]

const itemVariants = {
  hidden: { opacity: 0, y: 40 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.5, ease: 'easeOut' },
  },
}

export function ExperienceTimeline() {
  const { t } = useLanguage()
  const timeline = t.experience.items

  return (
    <section id="experience" className="max-w-4xl mx-auto px-6 py-20">
      <motion.div
        initial={{ opacity: 0 }}
        whileInView={{ opacity: 1 }}
        viewport={{ once: true }}
        transition={{ duration: 0.6 }}
        className="mb-16"
      >
        <h2 className="text-4xl font-bold mb-4">{t.experience.title}</h2>
        <p className="text-lg text-gray-600 dark:text-gray-400">
          {t.experience.subtitle}
        </p>
      </motion.div>

      <div className="relative">
        {/* Timeline line */}
        <div className="absolute left-0 md:left-1/2 top-0 bottom-0 w-1 bg-gradient-to-b from-blue-500 via-purple-500 to-green-500 md:transform md:-translate-x-1/2" />

        {/* Timeline items */}
        <div className="space-y-12">
          {timeline.map((item, index) => (
            <motion.div
              key={item.company}
              variants={itemVariants}
              initial="hidden"
              whileInView="visible"
              viewport={{ once: true, margin: "-100px" }}
              className="relative pl-8 md:pl-0"
            >
              {/* Timeline dot */}
              <div className={`absolute left-0 md:left-1/2 top-2 w-4 h-4 rounded-full bg-gradient-to-br ${colors[index]} transform md:-translate-x-1/2 -translate-x-1.5 border-4 border-white dark:border-gray-950 shadow-lg`} />

              {/* Content card */}
              <div className={index % 2 === 0 ? 'md:w-1/2 md:pr-8' : 'md:w-1/2 md:ml-auto md:pl-8'}>
                <div className="bg-white dark:bg-gray-900 rounded-lg p-6 border border-gray-200 dark:border-gray-700 hover:shadow-lg transition-shadow">
                  <div className="flex items-start justify-between mb-3">
                    <div>
                      <h3 className="text-xl font-bold text-gray-900 dark:text-white">
                        {item.company}
                      </h3>
                      <p className="text-sm font-semibold text-blue-600 dark:text-blue-400">
                        {item.role}
                      </p>
                    </div>
                    <div className="flex flex-col items-end gap-1 ml-4">
                      <span className="text-xs font-mono text-gray-500 dark:text-gray-400 whitespace-nowrap">
                        {item.period}
                      </span>
                      {index === 0 && (
                        <CIBadge repo="rock/homelab" forgejoUrl="https://forgejo.riotpiao.com/rock/homelab" />
                      )}
                    </div>
                  </div>

                  <p className="text-sm text-gray-700 dark:text-gray-300 mb-3">
                    {item.description}
                  </p>

                  <div className="flex flex-wrap gap-2 mb-4">
                    {skills[index]?.map((skill) => (
                      <span key={skill} className="text-xs px-3 py-1 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300">
                        {skill}
                      </span>
                    ))}
                  </div>

                  {links[index] && (
                    <a
                      href={links[index]!}
                      target={links[index]!.startsWith('#') ? '_self' : '_blank'}
                      rel="noopener noreferrer"
                      className="text-xs font-semibold text-blue-600 dark:text-blue-400 hover:underline"
                    >
                      {linkTexts[index] || 'View Product →'}
                    </a>
                  )}
                </div>
              </div>
            </motion.div>
          ))}
        </div>
      </div>
    </section>
  )
}
