"use client";

import { useRef, useState, useCallback } from "react";
import { LuCamera, LuUpload, LuFolderOpen, LuSettings, LuFileImage } from "react-icons/lu";
import { useCamera } from "../hook/useCamera";
import { CameraModal } from "../components/CameraModal";
import { useFieldsConfig } from "./FieldsConfigContext";

interface Props {
  onFilesSelected: (files: FileList | null) => void;
  categories: Array<{ id: string; name: string; icon: string | null; color: string | null }>;
  selectedCategory: string;
  onCategoryChange: (categoryId: string) => void;
}

export default function Step1SelectMethod({
  onFilesSelected,
  categories,
  selectedCategory,
  onCategoryChange
}: Props) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { isCameraOpen, stream, openCamera, closeCamera, takePicture } = useCamera(onFilesSelected);
  const { openModal } = useFieldsConfig();
  const [isDragOver, setIsDragOver] = useState(false);

  /* Fallback para cámara nativa en móviles (cuando no hay HTTPS) */
  const cameraInputRef = useRef<HTMLInputElement>(null);

  const handleCameraClick = () => {
    if (!selectedCategory) {
      alert("Por favor, selecciona una categoría primero");
      return;
    }

    // Si no hay soporte para getUserMedia (ej. HTTP en móvil), usar input nativo
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      cameraInputRef.current?.click();
      return;
    }

    openCamera();
  };

  const handleFileClick = () => {
    if (!selectedCategory) {
      alert("Por favor, selecciona una categoría primero");
      return;
    }
    fileInputRef.current?.click();
  };

  // Drag & Drop handlers
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    
    if (!selectedCategory) {
      alert("Por favor, selecciona una categoría primero");
      return;
    }

    const files = e.dataTransfer.files;
    if (files && files.length > 0) {
      const validFiles = Array.from(files).filter(
        file => file.type.startsWith('image/') || file.type === 'application/pdf'
      );
      
      if (validFiles.length === 0) {
        alert("Por favor, sube solo imágenes o archivos PDF");
        return;
      }

      const dataTransfer = new DataTransfer();
      validFiles.forEach(file => dataTransfer.items.add(file));
      onFilesSelected(dataTransfer.files);
    }
  }, [selectedCategory, onFilesSelected]);

  const isDisabled = !selectedCategory;

  return (
    <>
      {/* Selector de Categoría */}
      <div className="mb-8">
        <div className="flex justify-between items-center mb-3">
          <label className="block text-sm font-semibold text-text">
            Categoría del Documento <span className="text-destructive">*</span>
          </label>
          <button
            onClick={openModal}
            className="text-xs flex items-center gap-1.5 text-primary hover:text-primary-hover transition-colors font-medium focus-ring px-2 py-1 rounded"
          >
            <LuSettings size={14} />
            Configurar Campos
          </button>
        </div>
        {categories.length === 0 ? (
          <div className="bg-warning-background border border-warning-border rounded-xl p-4 flex items-start gap-3">
            <span className="text-xl">⚠️</span>
            <p className="text-sm text-warning-foreground">
              No hay categorías disponibles. Por favor, contacta a un administrador para crear categorías.
            </p>
          </div>
        ) : (
          <>
            <select
              value={selectedCategory}
              onChange={(e) => onCategoryChange(e.target.value)}
              className="w-full px-4 py-3 border border-border-subtle rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent text-base bg-background appearance-none cursor-pointer transition-all hover:border-primary/50"
              required
              aria-label="Seleccionar categoría del documento"
            >
              <option value="">Selecciona una categoría...</option>
              {categories.map((cat) => (
                <option key={cat.id} value={cat.id}>
                  {cat.icon} {cat.name}
                </option>
              ))}
            </select>
            <p className="text-xs text-text-muted mt-2">
              Selecciona la categoría para optimizar la detección de campos.
            </p>
          </>
        )}
      </div>

      {/* Métodos de captura */}
      <div className="text-center mb-6">
        <h3 className="font-bold text-text text-lg">Selecciona un método</h3>
        <p className="text-sm text-text-muted mt-1">
          Toma una foto o sube un archivo desde tu dispositivo
        </p>
      </div>

      {/* Drag & Drop Zone */}
      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        className={`mb-6 border-2 border-dashed rounded-2xl p-8 text-center transition-all duration-200 ${
          isDragOver
            ? "border-primary bg-primary-faint scale-[1.02]"
            : isDisabled
              ? "border-border-subtle bg-background-alt cursor-not-allowed opacity-50"
              : "border-border-subtle bg-background hover:border-primary/50 hover:bg-primary-faint/30 cursor-pointer"
        }`}
        onClick={!isDisabled ? handleFileClick : undefined}
        role="button"
        tabIndex={isDisabled ? -1 : 0}
        aria-label="Zona para arrastrar archivos o hacer clic para seleccionar"
        onKeyDown={(e) => {
          if (!isDisabled && (e.key === 'Enter' || e.key === ' ')) {
            handleFileClick();
          }
        }}
      >
        <div className={`w-16 h-16 mx-auto rounded-full flex items-center justify-center mb-4 transition-colors ${
          isDragOver ? "bg-primary text-primary-foreground" : isDisabled ? "bg-background-alt" : "bg-primary-faint"
        }`}>
          <LuUpload className={`h-8 w-8 ${isDragOver ? "text-primary-foreground" : isDisabled ? "text-text-subtle" : "text-primary"}`} />
        </div>
        <p className={`font-bold text-lg mb-1 ${isDragOver ? "text-primary" : ""}`}>
          {isDragOver ? "¡Suelta los archivos aquí!" : "Arrastra y suelta archivos aquí"}
        </p>
        <p className="text-sm text-text-muted mb-3">
          o haz clic para explorar
        </p>
        <div className="flex items-center justify-center gap-2 text-xs text-text-subtle">
          <span className="bg-background-alt px-2 py-1 rounded">JPG</span>
          <span className="bg-background-alt px-2 py-1 rounded">PNG</span>
          <span className="bg-background-alt px-2 py-1 rounded">PDF</span>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
        {/* Tomar Foto */}
        <button
          type="button"
          onClick={handleCameraClick}
          disabled={isDisabled}
          className={`group flex flex-col items-center justify-center text-center p-6 border-2 rounded-2xl transition-all duration-200 focus-ring ${
            isDisabled
              ? "bg-background-alt border-border-subtle cursor-not-allowed opacity-50"
              : "cursor-pointer hover:bg-primary-faint hover:border-primary border-border-subtle hover:shadow-md"
          }`}
          aria-label="Tomar foto con la cámara"
        >
          <div className={`w-14 h-14 rounded-full flex items-center justify-center mb-4 transition-all group-hover:scale-110 ${
            isDisabled ? "bg-background-alt" : "bg-primary-faint group-hover:bg-primary-subtle"
          }`}>
            <LuCamera className={`h-7 w-7 ${isDisabled ? "text-text-subtle" : "text-primary"}`} />
          </div>
          <p className={`font-bold text-lg ${isDisabled ? "text-text-subtle" : "text-text"}`}>
            Tomar Foto
          </p>
          <p className={`text-sm mt-1 ${isDisabled ? "text-text-subtle" : "text-text-muted"}`}>
            Usa tu cámara
          </p>
        </button>

        {/* Subir Archivo */}
        <button
          type="button"
          onClick={handleFileClick}
          disabled={isDisabled}
          className={`group flex flex-col items-center justify-center text-center p-6 border-2 rounded-2xl transition-all duration-200 focus-ring ${
            isDisabled
              ? "bg-background-alt border-border-subtle cursor-not-allowed opacity-50"
              : "cursor-pointer hover:bg-success-background hover:border-success-border border-border-subtle hover:shadow-md"
          }`}
          aria-label="Subir archivo desde el dispositivo"
        >
          <div className={`w-14 h-14 rounded-full flex items-center justify-center mb-4 transition-all group-hover:scale-110 ${
            isDisabled ? "bg-background-alt" : "bg-success-background group-hover:bg-success-border/50"
          }`}>
            <LuFileImage className={`h-7 w-7 ${isDisabled ? "text-text-subtle" : "text-success"}`} />
          </div>
          <p className={`font-bold text-lg ${isDisabled ? "text-text-subtle" : "text-text"}`}>
            Examinar Archivos
          </p>
          <p className={`text-sm mt-1 ${isDisabled ? "text-text-subtle" : "text-text-muted"}`}>
            JPG, PNG, PDF
          </p>
        </button>
      </div>

      {/* Input oculto para subir archivos */}
      <input
        type="file"
        accept="image/*,.pdf"
        ref={fileInputRef}
        onChange={(e) => onFilesSelected(e.target.files)}
        className="hidden"
        multiple
        aria-hidden="true"
      />

      {/* Input oculto para cámara nativa (Fallback) */}
      <input
        type="file"
        accept="image/*"
        capture="environment"
        ref={cameraInputRef}
        onChange={(e) => onFilesSelected(e.target.files)}
        className="hidden"
        aria-hidden="true"
      />

      {/* Modal de Cámara */}
      <CameraModal
        isOpen={isCameraOpen}
        stream={stream}
        onClose={closeCamera}
        onCapture={takePicture}
      />
    </>
  );
}