import { useRef, useState } from 'react';
import { fileToBase64, resizeAvatarImage, UndecodableImageError } from '../imageUtils';
import { hasConsent, setConsent } from '../storage';
import type { WidgetTranslations } from '../i18n';

interface AvatarUploadProps {
  onAvatarSaved: (imageData: string) => void;
  onCancel?: () => void;
  t: WidgetTranslations['upload'];
  // Pre-existing saved avatar (e.g. a returning visitor routed back here only
  // to re-confirm consent). Seeding the preview from it opens the component
  // directly in the preview+consent state instead of forcing a new file pick.
  initialPreview?: string | null;
}

export function AvatarUpload({ onAvatarSaved, onCancel, t, initialPreview }: AvatarUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [preview, setPreview] = useState<string | null>(initialPreview ?? null);
  const [isProcessing, setIsProcessing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [consented, setConsented] = useState(hasConsent());

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

    setError(null);

    try {
      setIsProcessing(true);
      const base64 = await fileToBase64(file);
      const resized = await resizeAvatarImage(base64);
      setPreview(resized);
    } catch (err) {
      // Refuse only when the image is genuinely undecodable; anything the
      // browser can decode is normalized and used.
      setError(err instanceof UndecodableImageError ? t.unreadableImage : t.processingFailed);
      console.error('Error processing image:', err);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleConfirm = () => {
    // Consent is required before we ever generate an AI try-on from the shopper's photo.
    if (preview && consented) {
      onAvatarSaved(preview);
      // Reset file input for next upload
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleConsentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const checked = e.target.checked;
    setConsented(checked);
    if (checked) {
      setConsent();
    }
  };

  const handleRetake = () => {
    setPreview(null);
    setError(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    e.stopPropagation();

    const files = e.dataTransfer.files;
    if (files.length > 0) {
      const file = files[0];
      // Simulate file input change event
      const event = {
        target: {
          files: { 0: file, length: 1 },
        },
      } as unknown as React.ChangeEvent<HTMLInputElement>;
      handleFileSelect(event);
    }
  };

  return (
    <div className="aisthetix-avatar-upload">
      <div className="aisthetix-avatar-upload-header">
        <h3>{t.title}</h3>
        <p>{t.description}</p>
      </div>

      {error && <div className="aisthetix-error-message">{error}</div>}

      {!preview ? (
        <div
          className="aisthetix-upload-area"
          onDragOver={handleDragOver}
          onDrop={handleDrop}
        >
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={handleFileSelect}
            className="aisthetix-file-input"
            id="avatar-file-input"
            disabled={isProcessing}
          />
          <label htmlFor="avatar-file-input" className="aisthetix-upload-label">
            {isProcessing ? (
              <div className="aisthetix-spinner" />
            ) : (
              <>
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="aisthetix-upload-icon"
                >
                  <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />
                  <polyline points="17 8 12 3 7 8" />
                  <line x1="12" y1="3" x2="12" y2="15" />
                </svg>
                <span>{t.clickOrDrag}</span>
                <span className="aisthetix-upload-hint">{t.fileHint}</span>
              </>
            )}
          </label>
        </div>
      ) : (
        <div className="aisthetix-preview-area">
          <img
            src={preview}
            alt={t.title}
            className="aisthetix-preview-image ph-no-capture"
          />
          <label className="aisthetix-consent">
            <input
              type="checkbox"
              checked={consented}
              onChange={handleConsentChange}
            />
            <span>{t.consent}</span>
          </label>
          <div className="aisthetix-preview-actions">
            <button
              type="button"
              onClick={handleRetake}
              className="aisthetix-btn aisthetix-btn-secondary"
            >
              {t.chooseDifferent}
            </button>
            <button
              type="button"
              onClick={handleConfirm}
              className="aisthetix-btn aisthetix-btn-primary"
              disabled={isProcessing || !consented}
            >
              {t.useThis}
            </button>
          </div>
        </div>
      )}

      {onCancel && !preview && (
        <button
          type="button"
          onClick={onCancel}
          className="aisthetix-btn aisthetix-btn-text"
        >
          {t.cancel}
        </button>
      )}

      <div className="aisthetix-privacy-note">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        >
          <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
          <path d="M7 11V7a5 5 0 0110 0v4" />
        </svg>
        <span>{t.privacyNote}</span>
      </div>
    </div>
  );
}
