import React, { useState } from 'react';
import ImageInput from './image-input';

export function ImageInputDemo() {
  const [selectedImage, setSelectedImage] = useState<File | string | null>(null);
  const [validationResult, setValidationResult] = useState<any>(null);
  const [demoLog, setDemoLog] = useState<string[]>([]);

  const log = (message: string) => {
    const timestamp = new Date().toLocaleTimeString();
    setDemoLog(prev => [`[${timestamp}] ${message}`, ...prev.slice(0, 4)]);
  };

  const handleImageChange = (value: File | string | null) => {
    setSelectedImage(value);
    log(`Image ${value ? 'selected' : 'cleared'}: ${value instanceof File ? value.name : value}`);
  };

  const handleValidation = (result: any) => {
    setValidationResult(result);
    log(`Validation: ${result.isValid ? 'Valid' : 'Invalid'} - ${result.error || 'OK'}`);
  };

  const handleUploadToServer = async () => {
    if (!selectedImage) return;

    log('Uploading to server...');
    
    // Simulate server upload
    await new Promise(resolve => setTimeout(resolve, 2000));
    
    log('Upload completed successfully!');
  };

  return (
    <div className="max-w-2xl mx-auto p-6 space-y-6">
      <div>
        <h1 className="text-2xl font-bold mb-2">ImageInput Component Demo</h1>
        <p className="text-gray-600">
          This demo showcases the ImageInput component with both file upload and URL input modes.
          Try selecting an image file or entering an image URL to see validation and preview in action.
        </p>
      </div>

      {/* ImageInput Component */}
      <div className="border rounded-lg p-6">
        <ImageInput
          value={selectedImage}
          onChange={handleImageChange}
          onValidation={handleValidation}
          disabled={false}
          showPreview={true}
          className="space-y-4"
        />
      </div>

      {/* Demo Actions */}
      {selectedImage && (
        <div className="flex gap-4">
          <button
            onClick={handleUploadToServer}
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
          >
            Simulate Upload
          </button>
          <button
            onClick={() => {
              setSelectedImage(null);
              setValidationResult(null);
              setDemoLog([]);
            }}
            className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
          >
            Reset Demo
          </button>
        </div>
      )}

      {/* Status Display */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Validation Status */}
        <div className="border rounded-lg p-4">
          <h3 className="font-semibold mb-2">Validation Status</h3>
          {validationResult ? (
            <div className="space-y-2 text-sm">
              <div>
                <span className="font-medium">Valid:</span>{' '}
                <span className={validationResult.isValid ? 'text-green-600' : 'text-red-600'}>
                  {validationResult.isValid ? 'Yes' : 'No'}
                </span>
              </div>
              {validationResult.error && (
                <div>
                  <span className="font-medium">Error:</span>{' '}
                  <span className="text-red-600">{validationResult.error}</span>
                </div>
              )}
              {validationResult.detectedType && (
                <div>
                  <span className="font-medium">Type:</span> {validationResult.detectedType}
                </div>
              )}
              {validationResult.filename && (
                <div>
                  <span className="font-medium">Filename:</span> {validationResult.filename}
                </div>
              )}
            </div>
          ) : (
            <p className="text-gray-500 text-sm">No validation performed yet</p>
          )}
        </div>

        {/* Activity Log */}
        <div className="border rounded-lg p-4">
          <h3 className="font-semibold mb-2">Activity Log</h3>
          <div className="space-y-1 text-sm font-mono bg-gray-50 p-2 rounded max-h-32 overflow-y-auto">
            {demoLog.length > 0 ? (
              demoLog.map((entry, index) => (
                <div key={index} className="text-gray-700">
                  {entry}
                </div>
              ))
            ) : (
              <p className="text-gray-500">No activity yet</p>
            )}
          </div>
        </div>
      </div>

      {/* Code Example */}
      <div className="border rounded-lg p-4">
        <h3 className="font-semibold mb-2">Usage Example</h3>
        <pre className="bg-gray-100 p-3 rounded text-sm overflow-x-auto">
{`import { ImageInput } from './components/ui/image-input';

function MyComponent() {
  const [image, setImage] = useState<File | string | null>(null);

  return (
    <ImageInput
      value={image}
      onChange={setImage}
      onValidation={(result) => {
        console.log('Validation:', result);
      }}
      showPreview={true}
      maxSize={5 * 1024 * 1024} // 5MB
    />
  );
}`}
        </pre>
      </div>
    </div>
  );
}

export default ImageInputDemo;