// app/components/admin/CommonComponents/ImageUpload.tsx
'use client';

import { useRef, useState } from 'react';
import Image from 'next/image';
import toast from 'react-hot-toast';

interface ImageUploadProps {
  value: string;
  onChange: (url: string) => void;
  uploadEndpoint?: string;
  uploadType?: string;
  label?: string;
  hint?: string;
  accept?: string;
  previewSize?: number;
  previewShape?: 'rounded' | 'circle';
  previewFallbackIcon?: React.ReactNode;
  altText?: string;
  onAltTextChange?: (value: string) => void;
  altTextPlaceholder?: string;
  className?: string;
}

const defaultImageIcon = (
  <svg className="w-8 h-8 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
  </svg>
);

const defaultAvatarIcon = (
  <svg className="w-8 h-8 text-var-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
  </svg>
);

export default function ImageUpload({
  value,
  onChange,
  uploadEndpoint = '/api/backend/admin/upload',
  uploadType = 'image',
  label = 'Upload Image',
  hint = 'JPG, PNG, or WebP. Max 5MB. Recommended: 1200×630 pixels.',
  accept = 'image/*',
  previewSize = 128,
  previewShape = 'rounded',
  previewFallbackIcon,
  altText,
  onAltTextChange,
  altTextPlaceholder = 'Describe the image for accessibility...',
  className = '',
}: ImageUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const shapeClass = previewShape === 'circle' ? 'rounded-full' : 'rounded-2xl';
  const fallbackIcon = previewFallbackIcon ?? (previewShape === 'circle' ? defaultAvatarIcon : defaultImageIcon);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', uploadType);

      const response = await fetch(uploadEndpoint, {
        method: 'POST',
        body: formData,
      });
      const data = await response.json();

      if (data.success) {
        onChange(data.url);
        toast.success('Image uploaded successfully');
      } else {
        toast.error(data.error || 'Failed to upload image');
      }
    } catch {
      toast.error('Failed to upload image');
    } finally {
      setUploading(false);
    }
  };

  const handleRemove = async () => {
    if (!value) return;
    try {
      await fetch(uploadEndpoint, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url: value }),
      });
    } catch {
      // Swallow
    }
    onChange('');
    if (fileInputRef.current) fileInputRef.current.value = '';
    toast.success('Image removed');
  };

  const showAltField = onAltTextChange !== undefined;

  return (
    <div className={`flex items-start space-x-6 ${className}`}>
      <div className="shrink-0">
        <div className="relative" style={{ width: previewSize, height: previewSize }}>
          {value ? (
            <>
              <Image
                src={value}
                alt={altText || 'Preview'}
                className={`${shapeClass} object-cover border-2 border-var-border`}
                width={previewSize}
                height={previewSize}
              />
              <button
                type="button"
                onClick={handleRemove}
                disabled={uploading}
                className="absolute -top-1 -right-1 bg-var-danger text-white rounded-full p-1 hover:bg-var-danger/80 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                title="Remove image"
              >
                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </>
          ) : (
            <div
              className={`${shapeClass} bg-var-surface-hover border-2 border-dashed border-var-border flex items-center justify-center`}
              style={{ width: previewSize, height: previewSize }}
            >
              {uploading ? (
                <svg className="animate-spin w-6 h-6 text-var-primary" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <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" />
                </svg>
              ) : (
                fallbackIcon
              )}
            </div>
          )}
        </div>
      </div>

      <div className="flex-1 space-y-3">
        <div>
          <label className="block text-sm font-medium text-var-text mb-2">{label}</label>
          <input
            ref={fileInputRef}
            type="file"
            accept={accept}
            onChange={handleFileChange}
            disabled={uploading}
            className="block w-full text-sm text-var-text-muted file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-sm file:font-medium file:bg-var-primary-muted file:text-var-primary hover:file:bg-var-primary/20 disabled:opacity-50 disabled:cursor-not-allowed"
          />
          {hint && <p className="text-sm text-var-text-muted mt-2">{hint}</p>}
          {uploading && (
            <p className="flex items-center gap-1.5 text-sm text-var-primary mt-2">
              <svg className="animate-spin w-3.5 h-3.5" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <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" />
              </svg>
              Uploading...
            </p>
          )}
        </div>

        {showAltField && (
          <div>
            <label className="block text-sm font-medium text-var-text mb-1.5">Alt Text</label>
            <input
              type="text"
              value={altText ?? ''}
              onChange={e => onAltTextChange(e.target.value)}
              placeholder={altTextPlaceholder}
              className="block w-full px-3.5 py-2.5 border border-var-border rounded-xl text-sm focus:ring-2 focus:ring-var-primary focus:border-var-primary bg-var-input text-var-text placeholder-var-text-muted transition-colors"
            />
          </div>
        )}
      </div>
    </div>
  );
}