'use client';

import { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { Upload, X, Image as ImageIcon } from 'lucide-react';
import Image from 'next/image';

interface ImageUploadProps {
  value?: string;
  onChange: (url: string) => void;
  onRemove?: () => void;
  className?: string;
  type?: string; // 'hero', 'default', etc.
  accept?: string;
  maxSize?: number;
  previewSize?: 'small' | 'medium' | 'large';
  compact?: boolean; // New prop for compact mode
}

export function ImageUpload({ 
  value, 
  onChange, 
  onRemove,
  className = '', 
  type = 'default', 
  accept = 'image/*',
  maxSize,
  previewSize = 'medium',
  compact = false 
}: ImageUploadProps) {
  const [preview, setPreview] = useState<string>(value || '');
  const [uploading, setUploading] = useState(false);
  const [dragActive, setDragActive] = useState(false);
  const [maxFileSize, setMaxFileSize] = useState(maxSize || (type === 'hero' ? 20 : 5));
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Fetch max file size from settings for non-hero uploads
  useEffect(() => {
    if (!maxSize && type !== 'hero') {
      const fetchSettings = async () => {
        try {
          const response = await fetch('/api/settings');
          if (response.ok) {
            const data = await response.json();
            if (data.settings?.maxFileSize) {
              setMaxFileSize(data.settings.maxFileSize);
            }
          }
        } catch (error) {
          console.error('Error fetching settings:', error);
        }
      };

      fetchSettings();
    }
  }, [type, maxSize]);

  useEffect(() => {
    setPreview(value || '');
  }, [value]);

  const compressImage = async (file: File, maxWidth: number = 1920, maxHeight: number = 1080, quality: number = 0.8): Promise<File> => {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      
      img.onload = () => {
        // Calculate new dimensions
        let { width, height } = img
        
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height)
          width *= ratio
          height *= ratio
        }
        
        canvas.width = width
        canvas.height = height
        
        // Draw and compress image
        ctx?.drawImage(img, 0, 0, width, height)
        
        canvas.toBlob((blob) => {
          if (blob) {
            const compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            resolve(compressedFile)
          } else {
            resolve(file) // Return original if compression fails
          }
        }, file.type, quality)
      }
      
      img.onerror = () => resolve(file) // Return original if loading fails
      img.src = URL.createObjectURL(file)
    })
  }

  const handleFileSelect = async (file: File) => {
    if (!file) return;

    // Validate file type
    const allowedTypes = accept === 'image/*' 
      ? ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
      : accept.split(',').map(type => type.trim());
    
    if (!allowedTypes.includes(file.type)) {
      alert('Invalid file type. Only ' + allowedTypes.join(', ') + ' are allowed.');
      return;
    }

    // Validate file size
    const maxSizeBytes = maxFileSize * 1024 * 1024; // Convert MB to bytes
    if (file.size > maxSizeBytes) {
      alert(`File too large. Maximum size is ${maxFileSize}MB.`);
      return;
    }

    setUploading(true);

    try {
      // Compress image for certain types (not for logos/icons)
      let fileToUpload = file;
      if (type !== 'logo' && type !== 'icon' && type !== 'polres' && type !== 'polres2' && type !== 'service-icon' && type !== 'service') {
        fileToUpload = await compressImage(file, 1920, 1080, 0.8);
        
        // Log compression results for debugging
        const originalSize = (file.size / 1024 / 1024).toFixed(2)
        const compressedSize = (fileToUpload.size / 1024 / 1024).toFixed(2)
        const compressionRatio = ((1 - fileToUpload.size / file.size) * 100).toFixed(1)
        
        if (parseFloat(compressionRatio) > 5) { // Only log if compression is significant
          console.log(`Image compression: ${originalSize}MB → ${compressedSize}MB (${compressionRatio}% reduction)`)
        }
      }
      
      const formData = new FormData();
      formData.append('file', fileToUpload);
      formData.append('type', type);

      // Use admin upload API for admin operations
      const uploadEndpoint = type === 'logo' || type === 'icon' || type === 'polres' || type === 'polres2' || type === 'service-icon' || type === 'service' ? '/api/admin/upload' : '/api/upload';

      // Prepare headers
      const headers: Record<string, string> = {};
      
      // Add authorization header for admin uploads
      if (type === 'logo' || type === 'icon' || type === 'polres' || type === 'polres2' || type === 'service-icon' || type === 'service') {
        const token = localStorage.getItem('adminToken');
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
      }

      const response = await fetch(uploadEndpoint, {
        method: 'POST',
        headers,
        body: formData,
      });

      const result = await response.json();

      if (result.success) {
        setPreview(result.url);
        onChange(result.url);
      } else {
        alert(result.error || 'Upload failed');
      }
    } catch (error) {
      console.error('Upload error:', error);
      alert('Upload failed');
    } finally {
      setUploading(false);
    }
  };

  const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);

    const file = e.dataTransfer.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleRemove = () => {
    setPreview('');
    onChange('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
    if (onRemove) {
      onRemove();
    }
  };

  // Size configurations
  const sizeConfig = {
    small: { width: 80, height: 80, class: 'h-20 w-20' },
    medium: { width: 120, height: 120, class: 'h-32 w-32' },
    large: { width: 200, height: 200, class: 'h-48 w-48' }
  };

  const config = sizeConfig[previewSize];

  // Compact mode - minimal design
  if (compact) {
    return (
      <div className={`flex items-center space-x-4 ${className}`}>
        {preview ? (
          <div className="relative flex-shrink-0">
            <div className={`relative ${config.class} border rounded-lg overflow-hidden bg-muted`}>
              <Image
                src={preview}
                alt="Preview"
                width={config.width}
                height={config.height}
                className="w-full h-full object-cover"
              />
              <Button
                type="button"
                variant="destructive"
                size="sm"
                onClick={handleRemove}
                className="absolute -top-2 -right-2 h-6 w-6 rounded-full p-0 cursor-pointer"
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          </div>
        ) : (
          <div 
            className={`relative ${config.class} border-2 border-dashed border-muted-foreground/25 rounded-lg flex items-center justify-center cursor-pointer hover:border-primary/50 transition-colors`}
            onClick={() => fileInputRef.current?.click()}
            onDragEnter={handleDrag}
            onDragLeave={handleDrag}
            onDragOver={handleDrag}
            onDrop={handleDrop}
          >
            <div className="text-center p-2">
              <ImageIcon className="h-6 w-6 mx-auto mb-1 text-muted-foreground" />
              <p className="text-xs text-muted-foreground">
                {uploading ? 'Uploading...' : 'Upload'}
              </p>
            </div>
          </div>
        )}
        
        <div className="flex-1 min-w-0">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => fileInputRef.current?.click()}
            disabled={uploading}
            className="cursor-pointer"
          >
            {uploading ? (
              <>
                <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-primary mr-2" />
                Uploading...
              </>
            ) : (
              <>
                <Upload className="h-3 w-3 mr-2" />
                {preview ? 'Change' : 'Choose'} Image
              </>
            )}
          </Button>
          <p className="text-xs text-muted-foreground mt-1">
            Max {maxFileSize}MB {type !== 'logo' && type !== 'icon' && type !== 'polres' && type !== 'polres2' && type !== 'service-icon' && type !== 'service' ? '(auto-compressed)' : ''}
          </p>
        </div>

        <input
          ref={fileInputRef}
          type="file"
          accept={accept}
          onChange={handleFileInput}
          className="hidden"
          disabled={uploading}
        />
      </div>
    );
  }

  // Full mode - original design but improved
  return (
    <div className={className}>
      <Input
        type="hidden"
        value={preview}
        onChange={(e) => onChange(e.target.value)}
      />

      {preview ? (
        <Card className="overflow-hidden">
          <CardContent className="p-4">
            <div className="flex items-start space-x-4">
              <div className={`relative ${config.class} flex-shrink-0 border rounded-lg overflow-hidden bg-muted`}>
                <Image
                  src={preview}
                  alt="Preview"
                  width={config.width}
                  height={config.height}
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium mb-2">Image uploaded successfully</p>
                <div className="flex space-x-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => fileInputRef.current?.click()}
                    disabled={uploading}
                    className="cursor-pointer"
                  >
                    <Upload className="h-3 w-3 mr-2" />
                    Change
                  </Button>
                  <Button
                    type="button"
                    variant="destructive"
                    size="sm"
                    onClick={handleRemove}
                    className="cursor-pointer"
                  >
                    <X className="h-3 w-3 mr-2" />
                    Remove
                  </Button>
                </div>
                <p className="text-xs text-muted-foreground mt-2">
                  Max size: {maxFileSize}MB {type !== 'logo' && type !== 'icon' && type !== 'polres' && type !== 'polres2' && type !== 'service-icon' && type !== 'service' ? '(auto-compressed to 1920x1080px, 80% quality)' : ''}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-4">
            <div
              className={`border-2 border-dashed rounded-lg p-4 text-center transition-colors ${
                dragActive
                  ? 'border-primary bg-primary/5'
                  : 'border-muted-foreground/25 hover:border-primary/50'
              }`}
              onDragEnter={handleDrag}
              onDragLeave={handleDrag}
              onDragOver={handleDrag}
              onDrop={handleDrop}
            >
              <div className="flex flex-col items-center space-y-3">
                <div className="p-2 bg-muted rounded-full">
                  <ImageIcon className="h-6 w-6 text-muted-foreground" />
                </div>
                <div>
                  <p className="text-sm font-medium">
                    {uploading ? 'Uploading...' : 'Drop image here or click to browse'}
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">
                    Supports: {accept.replace('image/', '').toUpperCase()} (max {maxFileSize}MB) {type !== 'logo' && type !== 'icon' && type !== 'polres' && type !== 'polres2' && type !== 'service-icon' && type !== 'service' ? '- auto-compressed' : ''}
                  </p>
                </div>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={uploading}
                  className="cursor-pointer"
                >
                  {uploading ? (
                    <>
                      <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-primary mr-2" />
                      Uploading...
                    </>
                  ) : (
                    <>
                      <Upload className="h-3 w-3 mr-2" />
                      Choose Image
                    </>
                  )}
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      <input
        ref={fileInputRef}
        type="file"
        accept={accept}
        onChange={handleFileInput}
        className="hidden"
        disabled={uploading}
      />
    </div>
  );
}