
import React, { useState } from 'react';
import JSZip from 'jszip';
import { CodeIcon } from './icons/CodeIcon';
import { DownloadIcon } from './icons/DownloadIcon';

interface GeneratedContentProps {
  htmlContent: string | null;
  readmeContent: string | null;
  isLoading: boolean;
  isSelected: boolean;
  progress: number;
  statusMessage: string;
}

const GeneratedContent: React.FC<GeneratedContentProps> = ({ htmlContent, readmeContent, isLoading, isSelected, progress, statusMessage }) => {
  const [isZipping, setIsZipping] = useState(false);

  const handleDownloadZip = async () => {
    if (!htmlContent || !readmeContent) return;

    setIsZipping(true);
    try {
      // 1. Get title from HTML content
      const getTitleFromHtml = (html: string): string => {
        const match = html.match(/<title>(.*?)<\/title>/i);
        // Sanitize and default title
        const pageTitle = match && match[1] ? match[1].trim() : 'interactive';
        return pageTitle.replace(/[^a-z0-9]/gi, '_').toLowerCase();
      };
      const title = getTitleFromHtml(htmlContent);

      // 2. Format the current date as YYYYMMDD
      const today = new Date();
      const yyyy = today.getFullYear();
      const mm = String(today.getMonth() + 1).padStart(2, '0'); // Months are 0-based
      const dd = String(today.getDate()).padStart(2, '0');
      const formattedDate = `${yyyy}${mm}${dd}`;
      
      // 3. Construct the filename
      const fileName = `${title}_${formattedDate}.zip`;

      const zip = new JSZip();

      // Add the main HTML file
      zip.file('index.html', htmlContent);

      // Add the README file
      zip.file('readMe.md', readmeContent);

      // Add the SLS config file
      const config = {
        entry: 'index.html',
      };
      zip.file('config.json', JSON.stringify(config, null, 2));

      // Generate the ZIP file
      const content = await zip.generateAsync({ type: 'blob' });

      // Trigger the download
      const link = document.createElement('a');
      link.href = URL.createObjectURL(content);
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href);

    } catch (error) {
      console.error('Failed to create ZIP file', error);
      // Ideally, show an error message to the user here
    } finally {
      setIsZipping(false);
    }
  };


  if (isLoading) {
    return (
      <div className="h-full flex flex-col items-center justify-center text-center text-gray-400 p-8">
        <div className="w-full max-w-md">
          <p className="font-semibold mb-3 text-gray-200">{statusMessage || 'Generating your interactive...'}</p>
          <div className="w-full bg-gray-700 rounded-full h-2.5 overflow-hidden">
            <div
              className="bg-primary h-2.5 rounded-full transition-all duration-300 ease-linear"
              style={{ width: `${progress}%` }}
              role="progressbar"
              aria-valuenow={progress}
              aria-valuemin={0}
              aria-valuemax={100}
            ></div>
          </div>
          <p className="text-sm mt-3 font-mono">{progress}%</p>
        </div>
      </div>
    );
  }

  if (htmlContent) {
    return (
      <div className="w-full h-full flex flex-col bg-gray-900 rounded-b-md">
        <div className="flex-shrink-0 bg-gray-700 p-2 flex items-center justify-end border-b border-gray-600">
          <button
            onClick={handleDownloadZip}
            disabled={isZipping || !readmeContent}
            className="bg-primary hover:bg-primary-hover text-white font-bold py-1 px-3 rounded-md text-sm flex items-center justify-center transition-colors disabled:bg-gray-600 disabled:cursor-wait"
            title={!readmeContent ? "README content is not available for download." : "Download as ZIP"}
          >
            {isZipping ? (
              <>
                <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Packaging...
              </>
            ) : (
              <>
                <DownloadIcon className="w-4 h-4 mr-2" />
                Download as ZIP
              </>
            )}
          </button>
        </div>
        <div className="flex-grow relative min-h-[350px]">
          <iframe
            srcDoc={htmlContent}
            title="Generated Interactive Content"
            className="w-full h-full border-0 bg-white"
            sandbox="allow-scripts allow-same-origin"
            style={{ minHeight: '350px' }}
          />
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col items-center justify-center text-center text-gray-500">
      <CodeIcon className="w-16 h-16 mb-4" />
      <h3 className="font-semibold text-lg text-gray-400">
        {isSelected ? 'Your generated interactive will appear here.' : 'Select an interactive type to begin.'}
      </h3>
      <p className="text-sm mt-1">
        {isSelected ? 'Fill in the details and click "Generate".' : 'Choose a template from the left panel.'}
      </p>
    </div>
  );
};

export default GeneratedContent;
