"use client"

import * as React from "react"
import { Search, Calendar, Briefcase, ChevronDown, ChevronUp, MapPin } from "lucide-react"

interface Job {
  company: string
  location?: string
  role: string
  date: string
  details: string[]
  tags: string[]
}

export function Experience() {
  const [searchQuery, setSearchQuery] = React.useState("")
  const [showAll, setShowAll] = React.useState(false)

  const jobs: Job[] = [
    {
      company: "Buadh Brath, Inc.",
      location: "Apex, North Carolina, USA",
      role: "President, Senior Consultant & Software Engineer",
      date: "Feb 2001 - Present",
      details: [
        "Advise and consult clients on technical solutions aligned with business goals, leveraging Drupal, Laravel, VueJS, and Wordpress for full-stack development.",
        "Direct full-cycle development of web applications with a strong focus on enterprise architecture and API integrations.",
        "Manage the maintenance and updates of mission-critical applications using PHP 7/8, Laravel, and NodeJS.",
        "Optimize performance and user experience with responsive design using HTML, CSS, jQuery, VueJS, and TypeScript.",
        "Integrate payment systems including Square, Paypal, Braintree, and Drupal e-commerce.",
        "Collaborate with stakeholders and engineering teams to streamline project management and deployment."
      ],
      tags: ["PHP", "Laravel", "VueJS", "Wordpress", "Drupal", "NodeJS", "TypeScript", "E-Commerce"]
    },
    {
      company: "Nicman Group LLC",
      role: "Senior Software Engineer (Consulting)",
      date: "Nov 2024 - Mar 2025",
      details: [
        "Enhanced and streamlined a legacy YII2 PHP framework application, improving performance and maintainability through code refactoring and automated testing with PHPUnit.",
        "Planned and executed the upgrade strategy for an on-premises OpenVMS system, coordinating cross-functional efforts to identify and address technical challenges.",
        "Collaborated with business stakeholders and engineering teams to modernize critical infrastructure, ensuring minimal downtime and a seamless transition.",
        "Coordinated project management tasks using GitHub, Slack, and Jira, while integrating agile methodologies and test-driven strategies through PHPUnit."
      ],
      tags: ["PHP", "YII2", "PHPUnit", "OpenVMS", "Agile", "Jira", "GitHub"]
    },
    {
      company: "eLuma Therapy LLC",
      location: "Lehi, Utah, USA (Remote)",
      role: "Senior Software Engineer (Employee)",
      date: "Dec 2022 - Jun 2024",
      details: [
        "Orchestrated a seamless data migration from legacy systems to modern software versions, minimizing disruptions for clinicians and educational institutions.",
        "Revamped the permission system and bolstered the automated testing suite, significantly enhancing software reliability and security in line with agile best practices.",
        "Maintained and optimized applications on a Debian Linux stack using PHP 8.x, Laravel, Docker, MySQL, and AWS services, utilizing BitBucket, Slack, and Jira."
      ],
      tags: ["PHP", "Laravel", "Docker", "MySQL", "AWS", "Debian", "BitBucket", "Agile"]
    },
    {
      company: "One Day Decisions, LLC",
      location: "Los Angeles Metropolitan Area",
      role: "CTO, Lead PHP Developer, Senior Architect",
      date: "Jun 2019 - May 2023",
      details: [
        "Assumed the CTO role to ensure seamless project continuity while providing technical leadership during a critical transition period.",
        "Implemented system analysis and established comprehensive documentation standards that improved team efficiency and streamlined onboarding processes.",
        "Architected and deployed a scalable email messaging feature and integrated robust version control practices, reinforcing code management and collaboration.",
        "Resolved critical issues within the payment processing system, restoring functionality and ensuring seamless service delivery."
      ],
      tags: ["CTO", "PHP", "Architecture", "Email Features", "Version Control", "Payments"]
    },
    {
      company: "St. Jude Children's Research Hospital - ALSAC",
      location: "Memphis, Tennessee, USA",
      role: "PHP Developer & Senior Software Engineer (Consulting)",
      date: "May 2021 - Jun 2022",
      details: [
        "Resolved complex PHP code conflicts during the migration from Red Hat Linux 7 to 8, ensuring system stability and accurate testing with Browserstack and PHPUnit.",
        "Refactored database interaction logic to align with upgraded infrastructure, improving performance and compatibility with PostgreSQL and MS SQL Server.",
        "Maintained version control integrity through regular validation and updates to Git repositories, enabling streamlined collaboration across development teams."
      ],
      tags: ["PHP", "Red Hat Linux", "PostgreSQL", "MS SQL Server", "Git", "PHPUnit", "Browserstack"]
    },
    {
      company: "Second Nature",
      location: "Raleigh, North Carolina, USA",
      role: "Lead PHP Developer & Senior Software Engineer (Consulting)",
      date: "Mar 2020 - Jan 2021",
      details: [
        "Integrated the corporate e-commerce platform with Zaius CRM via custom API solutions, significantly enhancing customer data management and cross-platform communication.",
        "Designed and developed new feature sets for internal systems, ensuring scalability, optimal performance, and alignment with strategic business objectives.",
        "Directed QA testing for key product releases, including comprehensive mobile testing with Browserstack, while proactively resolving critical bugs to maintain platform stability."
      ],
      tags: ["PHP", "Laravel", "MariaDB", "Zaius CRM API", "QA", "Mobile Testing", "Browserstack"]
    },
    {
      company: "Transcend Technology Group",
      location: "North America & India",
      role: "Senior Systems Analyst, Senior Software Engineer & Software Architect",
      date: "Apr 2016 - Present",
      details: [
        "Provide software design and development services to TTG's customers, large and small.",
        "Assist with custom software solutions involving Mobility, Digital, Big Data/Analytics, Cloud, Security, and Blockchain technologies."
      ],
      tags: ["Software Design", "Consulting", "Big Data", "Cloud", "Security", "Blockchain"]
    },
    {
      company: "Keshav Consulting Solutions, LLC",
      role: "Software Architect, Senior Systems Analyst & Senior Software Engineer",
      date: "2008 - Present",
      details: [
        "Provide software development, website development, and general IT consulting services to Keshav's clients."
      ],
      tags: ["Software Architect", "Web Development", "IT Consulting"]
    },
    {
      company: "Rental Ventures, Inc.",
      location: "Chapel Hill, North Carolina, USA",
      role: "Lead PHP Developer, Senior Software Engineer & Senior Architect (Consulting)",
      date: "Dec 2012 - Dec 2026",
      details: [
        "Led development and scaling of a large-scale web application powering 1,500+ global sites, utilizing PHP, Laravel, AJAX, JSON, XML, and RESTful APIs to deliver high-performance solutions.",
        "Architected and implemented new features while ensuring system reliability and high availability, and provided leadership across full-stack development and infrastructure management.",
        "Upgraded and deployed e-commerce systems using Braintree Payments, Square, and Paypal, and enhanced the mobile-friendly interface to meet modern user expectations.",
        "Mentored and guided a cross-functional IT team in modern web technologies including PHP, Laravel, MySQL, and JavaScript, driving technical excellence."
      ],
      tags: ["PHP", "Laravel", "E-Commerce", "Braintree", "Square", "Paypal", "REST API", "MySQL", "Mentoring"]
    },
    {
      company: "ANALYTRIX LTD",
      location: "Raleigh, North Carolina, USA",
      role: "Lead PHP Developer, Senior Systems Engineer & Network Administrator",
      date: "June 2007 - August 2018",
      details: [
        "Provided Software Engineer Development and Implementation roles in development of large Web Application.",
        "Designed and implemented multiple web sites with senior client management using both Joomla and Drupal CMS systems.",
        "Designed and wrote various documentation, including assistance with preparation of various proposals.",
        "Provided general technical advice, scripting, and system customization for operational and security requirements."
      ],
      tags: ["PHP", "Joomla", "Drupal", "System Customization", "Security", "Documentation"]
    },
    {
      company: "Foster Burgess, LLC",
      role: "Lead PHP Developer & Senior Software Engineer (Consulting)",
      date: "Jun 2017 - Apr 2018",
      details: [
        "Modernized a legacy 15-year-old infrastructure by architecting and deploying a scalable full-stack solution using Laravel and Vue.js, thereby improving operational efficiency.",
        "Oversaw the end-to-end development lifecycle from system design through implementation, delivering a unified platform that integrated inventory management, sales tracking, customer engagement, and advanced reporting.",
        "Managed a cross-functional development team by coordinating code quality reviews, sprint planning, and deployment schedules."
      ],
      tags: ["Laravel", "Vue.js", "Modernization", "Full-Stack", "Inventory System", "Sprint Planning"]
    },
    {
      company: "North Carolina Partnership For Children, Inc.",
      location: "Raleigh, North Carolina, USA",
      role: "Lead PHP Developer, Senior Software Engineer & Senior Architect (Consulting)",
      date: "Nov 2013 - Apr 2017",
      details: [
        "Enhanced and maintained a high-traffic internal Intranet used by hundreds of users, collaborating with cross-functional leadership to architect and deploy scalable PHP-based features.",
        "Engineered secure, role-based access control systems for database interactions and integrated advanced PDF generation from dynamic MySQL and MS SQL Server data to streamline reporting.",
        "Designed and maintained full-stack infrastructure including web, email, and database servers; implemented AJAX and JSON interfaces to elevate user experience."
      ],
      tags: ["PHP", "Intranet", "Role-Based Access", "PDF Generation", "MySQL", "MS SQL Server", "AJAX", "JSON"]
    },
    {
      company: "Piedmont Analytical Corporation",
      location: "Chapel Hill, North Carolina, USA",
      role: "Computer Systems Analyst",
      date: "Sep 2010 - Mar 2017",
      details: [
        "Provided client with physical data conversion services from Paradox Database to MySQL.",
        "Provided client with a small web application for data entry, query, and reporting purposes.",
        "Provided general technical advice and assistance to management personnel."
      ],
      tags: ["Data Conversion", "Paradox Database", "MySQL", "Web App"]
    },
    {
      company: "Security Management Consulting, Inc.",
      location: "Raleigh, North Carolina, USA",
      role: "Senior Software Engineer",
      date: "Oct 2010 - Dec 2014",
      details: [
        "Maintained large web application, including designing and implementing new features.",
        "Supported and extended Tomcat Java application.",
        "Provided software support to client's customers, including: American Electric Power (Ohio), Progress Energy (North Carolina and Florida), Conoco-Phillips (Texas), Medtronic (California), and Fifth Third Bank (Ohio).",
        "Provided Informix database support to client and customers and assisted with System and Network Administration."
      ],
      tags: ["Java", "Tomcat", "Informix Database", "System Administration"]
    },
    {
      company: "Effectiveness, Inc.",
      location: "Raleigh-Durham-Chapel Hill Area",
      role: "PHP Developer & Senior Software Engineer",
      date: "Apr 2008 - Mar 2012",
      details: [
        "Designed and implemented over a dozen web sites with senior client management using Drupal and Wordpress.",
        "Assisted client staff with System and Network Administration issues.",
        "Provided general technical advice and assistance to management."
      ],
      tags: ["PHP", "Drupal", "Wordpress", "System Administration"]
    },
    {
      company: "Triangle Aerial Surveys, Inc",
      role: "Senior Software Engineer, System & Network Administrator, CTO",
      date: "Sep 2001 - May 2009",
      details: [
        "Directed end-to-end system and network administration for client infrastructures, maintaining high availability and security across Linux-based environments and network servers.",
        "Architected and deployed custom web solutions in collaboration with executive stakeholders, aligning user experience with business goals.",
        "Provided strategic technical leadership and support for GIS and photogrammetry projects, including scripting for data conversions, workflow optimization, and producing detailed technical documentation."
      ],
      tags: ["Linux Admin", "Network Admin", "CTO", "GIS", "Scripting", "Documentation"]
    },
    {
      company: "Wilson-Cook Medical, Inc.",
      role: "Consultant",
      date: "Jan 2006 - Nov 2006",
      details: [
        "Provided computer consulting services to client."
      ],
      tags: ["Consulting"]
    },
    {
      company: "Hill-Rom Inc. a division of Hillenbrand, Inc.",
      location: "Cary, North Carolina, USA",
      role: "Senior Systems Analyst, Complaint Investigator (Consulting)",
      date: "Jun 2000 - Oct 2003",
      details: [
        "Conducted detailed failure investigations in response to customer complaints, contributing critical reports that supported successful FDA inspections and audits.",
        "Played an integral role in guiding the company through the FDA regulatory audit process, facilitating Hill-Rom's return to the marketplace after a voluntary suspension.",
        "Trained staff on failure investigation procedures and authored comprehensive Quality System and Engineering documents to support continuous improvement."
      ],
      tags: ["FDA Audits", "Complaint Investigator", "Failure Investigation", "Quality Systems", "Documentation"]
    },
    {
      company: "C-Mac Industries",
      location: "Creedmoor, North Carolina, USA",
      role: "Senior Computer Systems Analyst",
      date: "Jun 2001 - Oct 2001",
      details: [
        "Designed and implemented B2B websites using server-side PHP within an Apache environment, using Oracle databases.",
        "Supported source version control library and trained client staff in its use.",
        "Provided technical documentation of database and web site components."
      ],
      tags: ["PHP", "Apache", "Oracle Database", "Version Control", "Documentation"]
    },
    {
      company: "TELUS Communications",
      location: "Edmonton, Alberta, Canada",
      role: "Senior Computer Systems Analyst",
      date: "Sep 1999 - Dec 2000",
      details: [
        "Designed and developed web sites using Perl, Oracle, PL/SQL, ASP, MS Access, HTML, and Server-Side JavaScript.",
        "Evaluated Year 2000 Readiness of several hundred web sites hosted by client, including Perl, Java, and JavaScript code.",
        "Tested the web sites after corrections made by the staff programmers."
      ],
      tags: ["Perl", "PL/SQL", "Y2K Readiness", "Oracle", "ASP", "Testing"]
    },
    {
      company: "Enbridge Pipelines",
      location: "Edmonton, Alberta, Canada",
      role: "Senior Computer Systems Analyst",
      date: "Sep 1998 - Jun 1999",
      details: [
        "Evaluated and documented Year 2000 Readiness of infrastructure components.",
        "Provided documentation, web design, and programming to client UNIX System Administrators."
      ],
      tags: ["Y2K Readiness", "UNIX Admin", "Documentation", "Programming"]
    },
    {
      company: "McCullough Computer Consulting",
      role: "President",
      date: "1990 - 1999",
      details: [
        "Advised and consulted clients on custom software solutions, systems administration, and IT architecture."
      ],
      tags: ["President", "Consulting", "IT Architecture"]
    },
    {
      company: "ISM Alberta / Alberta Health Services",
      location: "Edmonton, Alberta, Canada",
      role: "Senior Computer Systems Analyst & Supervisor",
      date: "Nov 1994 - Sep 1998",
      details: [
        "Held a supervisory position on the Decision Support Environment (DSE) project, directing programmers involved with maintenance and improvement of products for government health analysis.",
        "Collaborated in the conceptual, logical, and physical design of the DSE project (a large client-server application).",
        "Designed and directed coding of most C and Pro*C code, and managed the technical manuals.",
        "Installed and maintained UNIX mail systems with automated pager notifications."
      ],
      tags: ["Supervisor", "C", "Pro*C", "UNIX Mail", "Client-Server", "Health Systems"]
    }
  ]

  // Filter jobs based on search query
  const filteredJobs = jobs.filter(
    (job) =>
      job.company.toLowerCase().includes(searchQuery.toLowerCase()) ||
      job.role.toLowerCase().includes(searchQuery.toLowerCase()) ||
      job.details.some((detail) => detail.toLowerCase().includes(searchQuery.toLowerCase())) ||
      job.tags.some((tag) => tag.toLowerCase().includes(searchQuery.toLowerCase()))
  )

  // Determine which jobs to display based on expand toggle and search query
  const displayedJobs = searchQuery
    ? filteredJobs // Show all matches if searching
    : showAll
    ? jobs // Show all if expanded
    : jobs.slice(0, 5) // Default to first 5

  return (
    <section id="experience" className="py-20 bg-muted/30 transition-colors duration-300">
      <div className="container mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        
        {/* Header Section */}
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-6 mb-12">
          <div>
            <h2 className="text-3xl font-bold tracking-tight text-foreground sm:text-4xl">
              Professional Experience
            </h2>
            <p className="mt-2 text-muted-foreground">
              A chronological history of my consulting engagements, CTO leadership, and engineering roles.
            </p>
          </div>

          {/* Search Box */}
          <div className="relative w-full md:w-80">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <input
              type="text"
              placeholder="Search by skill, company, or keyword..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full rounded-lg border border-border bg-background py-2 pl-10 pr-4 text-sm text-foreground placeholder-muted-foreground focus:border-cyan-500 focus:outline-hidden transition-colors"
              id="experience-search-input"
            />
          </div>
        </div>

        {/* Timeline List */}
        <div className="relative border-l border-border/60 ml-3 md:ml-6 space-y-10 pl-6 md:pl-8">
          {displayedJobs.map((job, idx) => (
            <div key={idx} className="relative group">
              {/* Timeline Bullet */}
              <div className="absolute -left-[31px] md:-left-[39px] top-1.5 flex h-6 w-6 items-center justify-center rounded-full border border-border bg-background text-muted-foreground group-hover:border-cyan-500 group-hover:text-cyan-500 transition-colors duration-300">
                <Briefcase className="h-3 w-3" />
              </div>

              {/* Job Card */}
              <div className="border border-border/40 bg-background rounded-xl p-5 md:p-6 shadow-xs hover:border-border/80 transition-all">
                <div className="flex flex-col md:flex-row md:items-start justify-between gap-2 border-b border-border/10 pb-4 mb-4">
                  <div>
                    <h3 className="text-lg font-bold text-foreground group-hover:text-cyan-600 dark:group-hover:text-cyan-400 transition-colors">
                      {job.role}
                    </h3>
                    <div className="text-sm font-semibold text-muted-foreground mt-0.5">
                      {job.company}
                    </div>
                  </div>

                  <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <Calendar className="h-3.5 w-3.5 text-cyan-500" />
                      {job.date}
                    </span>
                    {job.location && (
                      <span className="flex items-center gap-1">
                        <MapPin className="h-3.5 w-3.5 text-indigo-500" />
                        {job.location}
                      </span>
                    )}
                  </div>
                </div>

                {/* Job Bullet Points */}
                <ul className="list-disc pl-5 text-sm text-muted-foreground space-y-2 mb-4 leading-relaxed">
                  {job.details.map((detail, dIdx) => (
                    <li key={dIdx}>{detail}</li>
                  ))}
                </ul>

                {/* Badges / Tags */}
                <div className="flex flex-wrap gap-1.5">
                  {job.tags.map((tag, tIdx) => (
                    <span
                      key={tIdx}
                      className="inline-flex items-center rounded-full bg-muted/60 px-2 py-0.5 text-2xs font-medium text-muted-foreground border border-border/20"
                    >
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Empty State */}
        {displayedJobs.length === 0 && (
          <div className="text-center py-12 border border-dashed border-border rounded-xl bg-background/50">
            <p className="text-muted-foreground">No roles found matching "{searchQuery}"</p>
          </div>
        )}

        {/* Show More / Show Less Toggle Button */}
        {!searchQuery && jobs.length > 5 && (
          <div className="mt-12 flex justify-center">
            <button
              onClick={() => setShowAll(!showAll)}
              className="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-5 py-2.5 text-sm font-semibold text-foreground hover:bg-accent hover:text-accent-foreground shadow-xs transition-all cursor-pointer"
              id="experience-toggle-btn"
            >
              {showAll ? (
                <>
                  Show Less Roles
                  <ChevronUp className="h-4 w-4" />
                </>
              ) : (
                <>
                  Show All {jobs.length} Roles
                  <ChevronDown className="h-4 w-4" />
                </>
              )}
            </button>
          </div>
        )}

      </div>
    </section>
  )
}
