"use client";

import { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Image as ImageIcon, Upload, Link as LinkIcon } from "lucide-react";

interface ImageModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: (url: string, alt?: string) => void;
}

export const ImageModal = ({
  isOpen,
  onClose,
  onConfirm,
}: ImageModalProps) => {
  const [url, setUrl] = useState("");
  const [alt, setAlt] = useState("");
  const [file, setFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState("");
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleUrlSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (url.trim()) {
      onConfirm(url.trim(), alt.trim() || undefined);
      handleClose();
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (selectedFile && selectedFile.type.startsWith('image/')) {
      setFile(selectedFile);
      
      // Create preview URL
      const reader = new FileReader();
      reader.onload = (e) => {
        setPreviewUrl(e.target?.result as string);
      };
      reader.readAsDataURL(selectedFile);
    }
  };

  const handleFileUpload = async (e?: React.MouseEvent) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    
    if (!file) return;
    
    setUploading(true);
    try {
      // Create a data URL for the image
      const reader = new FileReader();
      reader.onload = (e) => {
        const dataUrl = e.target?.result as string;
        onConfirm(dataUrl, alt.trim() || file.name);
        handleClose();
      };
      reader.readAsDataURL(file);
    } catch (error) {
      console.error('Failed to process image:', error);
    } finally {
      setUploading(false);
    }
  };

  const handleClose = () => {
    setUrl("");
    setAlt("");
    setFile(null);
    setPreviewUrl("");
    setUploading(false);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
    onClose();
  };

  const handleButtonClick = (e: React.MouseEvent, action: () => void) => {
    e.preventDefault();
    e.stopPropagation();
    action();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      e.preventDefault();
      e.stopPropagation();
      handleClose();
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent 
        className="sm:max-w-md" 
        onKeyDown={handleKeyDown}
        onPointerDownOutside={(e) => {
          e.preventDefault();
          e.stopPropagation();
        }}
        onInteractOutside={(e) => {
          e.preventDefault();
          e.stopPropagation();
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <ImageIcon className="h-4 w-4" />
            Add Image
          </DialogTitle>
        </DialogHeader>

        <Tabs defaultValue="url" className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="url" className="flex items-center gap-2">
              <LinkIcon className="h-4 w-4" />
              URL
            </TabsTrigger>
            <TabsTrigger value="upload" className="flex items-center gap-2">
              <Upload className="h-4 w-4" />
              Upload
            </TabsTrigger>
          </TabsList>

          <TabsContent value="url" className="space-y-4">
            <form onSubmit={handleUrlSubmit} onClick={(e) => e.stopPropagation()}>
              <div className="grid gap-4 py-4">
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="image-url" className="text-right">
                    URL
                  </Label>
                  <Input
                    id="image-url"
                    type="url"
                    placeholder="https://example.com/image.jpg"
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    className="col-span-3"
                    autoFocus
                  />
                </div>
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label htmlFor="image-alt" className="text-right">
                    Alt Text
                  </Label>
                  <Input
                    id="image-alt"
                    placeholder="Description (optional)"
                    value={alt}
                    onChange={(e) => setAlt(e.target.value)}
                    className="col-span-3"
                  />
                </div>
              </div>
              
                             <DialogFooter>
                 <Button 
                   type="button" 
                   variant="outline" 
                   onClick={(e) => handleButtonClick(e, handleClose)}
                 >
                   Cancel
                 </Button>
                 <Button 
                   type="submit" 
                   disabled={!url.trim()}
                 >
                   Add Image
                 </Button>
               </DialogFooter>
            </form>
          </TabsContent>

          <TabsContent value="upload" className="space-y-4" onClick={(e) => e.stopPropagation()}>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="image-file" className="text-right">
                  File
                </Label>
                <div className="col-span-3">
                  <Input
                    id="image-file"
                    type="file"
                    accept="image/*"
                    onChange={handleFileSelect}
                    ref={fileInputRef}
                    className="cursor-pointer"
                  />
                </div>
              </div>
              
              {previewUrl && (
                <div className="grid grid-cols-4 items-center gap-4">
                  <Label className="text-right">Preview</Label>
                  <div className="col-span-3">
                    <img 
                      src={previewUrl} 
                      alt="Preview" 
                      className="max-w-full h-32 object-contain rounded border"
                    />
                  </div>
                </div>
              )}
              
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="upload-alt" className="text-right">
                  Alt Text
                </Label>
                <Input
                  id="upload-alt"
                  placeholder="Description (optional)"
                  value={alt}
                  onChange={(e) => setAlt(e.target.value)}
                  className="col-span-3"
                />
              </div>
            </div>
            
                         <DialogFooter>
               <Button 
                 type="button" 
                 variant="outline" 
                 onClick={(e) => handleButtonClick(e, handleClose)}
               >
                 Cancel
               </Button>
               <Button 
                 type="button"
                 onClick={handleFileUpload} 
                 disabled={!file || uploading}
               >
                 {uploading ? "Processing..." : "Add Image"}
               </Button>
             </DialogFooter>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}; 