'use client';

import { useEffect, useState } from 'react';
import { CodeExamplesWidget } from './CodeExamplesWidget';

/**
 * SelectedFileCodePreview Component
 *
 * Shows code snippets for uploading a selected file BEFORE upload.
 * Helps users understand they can either:
 * 1. Upload via UI button
 * 2. Copy code and run programmatically
 *
 * Layout:
 * - Mobile: Stacked vertically
 * - Desktop: 3-column grid (1 col preview + 2 cols code)
 */

interface SelectedFileCodePreviewProps {
  file: File;
  apiKey: string;
  apiBaseUrl: string;
  onCopy: (text: string) => void;
}

export const SelectedFileCodePreview = ({
  file,
  apiKey,
  apiBaseUrl,
  onCopy,
}: SelectedFileCodePreviewProps) => {
  const [previewUrl, setPreviewUrl] = useState<string>('');

  // Create and cleanup preview URL
  useEffect(() => {
    const objectUrl = URL.createObjectURL(file);
    setPreviewUrl(objectUrl);

    return () => {
      URL.revokeObjectURL(objectUrl);
    };
  }, [file]);

  const codeExamples = generateSelectedFileCodeExamples(file, apiKey, apiBaseUrl);

  return (
    <section className="space-y-4" aria-label="Selected File Code Preview">
      <div className="flex items-center justify-between">
        <h2 className="text-xl md:text-2xl font-bold text-white">
          Selected File - Code Preview
        </h2>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        {/* Column 1: Compact File Preview Card */}
        <div className="lg:col-span-1">
          <div className="p-4 bg-slate-900/80 backdrop-blur-sm border border-slate-700 rounded-xl h-full">
            {/* Image Preview - Compact */}
            <div className="aspect-video bg-slate-800 rounded-lg mb-3 overflow-hidden max-h-32">
              <img
                src={previewUrl}
                alt={`Preview of ${file.name}`}
                className="w-full h-full object-cover"
              />
            </div>

            {/* File Metadata */}
            <div className="space-y-2">
              <p
                className="text-white text-sm font-medium truncate"
                title={file.name}
              >
                {file.name}
              </p>

              <div className="flex flex-wrap items-center gap-2 text-xs">
                {/* File Size */}
                <span className="px-2 py-1 bg-slate-700/50 text-gray-300 rounded">
                  {formatFileSize(file.size)}
                </span>

                {/* File Type Badge */}
                <span className="px-2 py-1 bg-purple-600/20 text-purple-400 rounded border border-purple-600/30">
                  {getFileType(file.name)}
                </span>
              </div>

              {/* Status Badge */}
              <div className="pt-2">
                <span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-600/20 text-amber-400 rounded border border-amber-600/30 text-xs font-medium">
                  <svg
                    className="w-3.5 h-3.5"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    aria-hidden="true"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                  Ready to Upload
                </span>
              </div>

              {/* Helper Text */}
              <p className="text-xs text-gray-500 pt-2">
                Click upload button or copy code to run programmatically
              </p>
            </div>
          </div>
        </div>

        {/* Columns 2-3: Code Examples Widget */}
        <div className="lg:col-span-2">
          <CodeExamplesWidget
            codeExamples={codeExamples}
            onCopy={onCopy}
            defaultTab="curl"
          />
        </div>
      </div>
    </section>
  );
};

/**
 * Generate production-ready code examples for selected file upload
 *
 * Pattern: Users navigate to their folder, then run the upload command.
 * This matches how real workflows work - users know where their file is.
 */
const generateSelectedFileCodeExamples = (
  file: File,
  apiKey: string,
  apiBaseUrl: string
) => {
  const fileName = file.name;

  return {
    curl: `# Navigate to your images folder
cd /your/images/folder

# Upload the file
curl -X POST "${apiBaseUrl}/api/upload" \\
  -H "X-API-Key: ${apiKey}" \\
  -F "file=@${fileName}"`,

    fetch: `// Set your images folder path
const imagePath = '/your/images/folder';
const fileName = '${fileName}';

// For Node.js with fs module:
const fs = require('fs');
const FormData = require('form-data');
const formData = new FormData();
formData.append('file', fs.createReadStream(\`\${imagePath}/\${fileName}\`));

fetch('${apiBaseUrl}/api/upload', {
  method: 'POST',
  headers: {
    'X-API-Key': '${apiKey}'
  },
  body: formData
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));`,

    rest: `# From your images folder: /your/images/folder

POST ${apiBaseUrl}/api/upload
Headers:
  X-API-Key: ${apiKey}
  Content-Type: multipart/form-data

Body (form-data):
  file: @${fileName}`,
  };
};

/**
 * Format file size in human-readable format
 */
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
};

/**
 * Extract file type from filename
 */
const getFileType = (filename: string): string => {
  const extension = filename.split('.').pop()?.toUpperCase();
  if (extension === 'JPG' || extension === 'JPEG') return 'JPEG';
  if (extension === 'PNG') return 'PNG';
  if (extension === 'WEBP') return 'WebP';
  if (extension === 'GIF') return 'GIF';
  return extension || 'FILE';
};
