"use client";

import { useState, useRef, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Camera, Upload, X, User, Building, Image as ImageIcon } from "lucide-react";
import Image from "next/image";

export type FotoType = "logo" | "foto-personal" | "foto-institucion";

interface FotoUploadProps {
  tipo: FotoType;
  titulo: string;
  descripcion?: string;
  value: File | null;
  preview: string | null;
  onChange: (file: File | null, preview: string | null) => void;
  required?: boolean;
  maxSizeMB?: number;
}

export default function FotoUpload({
  tipo,
  titulo,
  descripcion,
  value,
  preview,
  onChange,
  required = false,
  maxSizeMB = 5
}: FotoUploadProps) {
  const [isDragging, setIsDragging] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const getIcon = () => {
    switch (tipo) {
      case "logo":
        return <Building className="h-12 w-12 text-gray-400" />;
      case "foto-personal":
        return <User className="h-12 w-12 text-gray-400" />;
      case "foto-institucion":
        return <ImageIcon className="h-12 w-12 text-gray-400" />;
      default:
        return <Camera className="h-12 w-12 text-gray-400" />;
    }
  };

  const getPlaceholderText = () => {
    switch (tipo) {
      case "logo":
        return "Sube el logo de tu institución";
      case "foto-personal":
        return "Sube una foto de la cintura hacia arriba";
      case "foto-institucion":
        return "Sube el logo o imagen representativa";
      default:
        return "Arrastra una imagen o haz clic para seleccionar";
    }
  };

  const validateFile = (file: File): boolean => {
    setError(null);

    // Validar tipo
    const validTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
    if (!validTypes.includes(file.type)) {
      setError("Solo se permiten imágenes (JPG, PNG, WEBP, GIF)");
      return false;
    }

    // Validar tamaño
    const maxBytes = maxSizeMB * 1024 * 1024;
    if (file.size > maxBytes) {
      setError(`La imagen no debe superar los ${maxSizeMB}MB`);
      return false;
    }

    return true;
  };

  const handleFile = useCallback((file: File) => {
    if (!validateFile(file)) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      onChange(file, e.target?.result as string);
    };
    reader.readAsDataURL(file);
  }, [onChange]);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);

    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }, [handleFile]);

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

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

  const handleRemove = () => {
    onChange(null, null);
    setError(null);
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };

  const handleClick = () => {
    inputRef.current?.click();
  };

  // Determinar el aspecto del marco según el tipo
  const getFrameClasses = () => {
    if (tipo === "logo") {
      return "aspect-square max-w-[200px]"; // Marco cuadrado para logos
    }
    return "aspect-[3/4] max-w-[200px]"; // Marco vertical para fotos personales (3:4)
  };

  return (
    <div className="space-y-2">
      <label className="block text-sm font-medium text-gray-700">
        {titulo} {required && <span className="text-red-500">*</span>}
      </label>
      {descripcion && (
        <p className="text-xs text-gray-500 mb-2">{descripcion}</p>
      )}

      <Card className={`border-2 border-dashed transition-colors ${isDragging ? 'border-[#00B8D4] bg-[#00B8D4]/5' : 'border-gray-300 hover:border-[#00B8D4]'}`}>
        <CardContent className="p-4">
          {preview ? (
            <div className="flex flex-col items-center">
              <div className={`relative ${getFrameClasses()} w-full mx-auto overflow-hidden rounded-lg bg-gray-100`}>
                <Image
                  src={preview}
                  alt={titulo}
                  fill
                  className="object-cover"
                />
                <Button
                  type="button"
                  variant="destructive"
                  size="sm"
                  className="absolute top-2 right-2 h-8 w-8 p-0 rounded-full"
                  onClick={handleRemove}
                >
                  <X className="h-4 w-4" />
                </Button>
              </div>
              <p className="text-sm text-gray-600 mt-2 text-center">
                {value?.name}
              </p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="mt-2"
                onClick={handleClick}
              >
                Cambiar imagen
              </Button>
            </div>
          ) : (
            <div
              className="flex flex-col items-center justify-center py-8 cursor-pointer"
              onDrop={handleDrop}
              onDragOver={handleDragOver}
              onDragLeave={handleDragLeave}
              onClick={handleClick}
            >
              <div className={`relative ${getFrameClasses()} w-full mx-auto flex items-center justify-center border-2 border-dashed border-gray-300 rounded-lg bg-gray-50`}>
                {getIcon()}
              </div>
              <p className="text-sm text-gray-600 mt-4 text-center">
                {getPlaceholderText()}
              </p>
              <p className="text-xs text-gray-400 mt-1">
                JPG, PNG, WEBP o GIF (máx. {maxSizeMB}MB)
              </p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="mt-3 text-[#00B8D4] border-[#00B8D4] hover:bg-[#00B8D4] hover:text-white"
              >
                <Upload className="h-4 w-4 mr-2" />
                Seleccionar imagen
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {error && (
        <p className="text-sm text-red-500">{error}</p>
      )}

      <input
        ref={inputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp,image/gif"
        onChange={handleInputChange}
        className="hidden"
      />
    </div>
  );
}
