'use client';
import { Terminal } from '@/components/common/Terminal';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { VercelService } from '@/src/services/VercelService';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { useState } from 'react';
import { FaGithub } from 'react-icons/fa';
import { VercelProjectProps, DeploymentEvent } from '@/types/deployment';

export function DeploymentHistory({ project }: VercelProjectProps) {
  const [expandedDeployment, setExpandedDeployment] = useState<string | null>(null);
  const [deploymentEvents, setDeploymentEvents] = useState<Record<string, DeploymentEvent[]>>({});
  const [loading, setLoading] = useState<Record<string, boolean>>({});

  const toggleDeployment = async (deploymentId: string) => {
    const newState = expandedDeployment === deploymentId ? null : deploymentId;
    setExpandedDeployment(newState);

    if (newState && !deploymentEvents[deploymentId]) {
      setLoading((prev) => ({ ...prev, [deploymentId]: true }));
      try {
        const events = await VercelService.getDeploymentEvents(deploymentId);
        setDeploymentEvents((prev) => ({ ...prev, [deploymentId]: events }));
      } finally {
        setLoading((prev) => ({ ...prev, [deploymentId]: false }));
      }
    }
  };

  return (
    <div>
      <h3 className='text-xl mt-4 font-semibold mb-4 text-white'>Deployment History</h3>
      <div className='space-y-4'>
        {project.latestDeployments?.map((deployment) => (
          <div key={deployment.id} className='space-y-2'>
            <div
              className='w-full border border-neutral-300 rounded-lg p-4 cursor-pointer hover:bg-neutral-800/50 transition-colors text-left'
              onClick={() => toggleDeployment(deployment.id)}
              role='button'
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  toggleDeployment(deployment.id);
                }
              }}
              aria-expanded={expandedDeployment === deployment.id}
              aria-label={`View deployment details from ${new Date(deployment.createdAt).toLocaleString()}`}
            >
              <div className='flex items-start justify-between mb-2'>
                <div className='flex items-center gap-2'>
                  <Badge variant={deployment.readyState === 'READY' ? 'default' : 'error'}>
                    {deployment.readyState}
                  </Badge>
                  <span className='text-sm text-neutral-300'>{new Date(deployment.createdAt).toLocaleString()}</span>
                </div>
                <Button variant='ghost' size='icon' className='h-10 w-10'>
                  {expandedDeployment === deployment.id ? (
                    <ChevronUp className='!h-full !w-full' />
                  ) : (
                    <ChevronDown className='!h-full !w-full' />
                  )}
                </Button>
              </div>
              <p className='text-sm mb-2 text-neutral-300'>{deployment.meta?.githubCommitMessage}</p>
              <div className='flex items-center gap-2 text-sm text-neutral-300'>
                <FaGithub />
                <span>{deployment.meta?.githubCommitSha?.slice(0, 7)}</span>
              </div>
            </div>

            {expandedDeployment === deployment.id && (
              <div className=''>
                <h4 className='text-lg font-semibold text-white mb-2'>Deployment Logs</h4>
                <Terminal logs={deploymentEvents[deployment.id] || []} loading={loading[deployment.id]} />
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
