import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Trash2, GripVertical, Image as ImageIcon, Upload,
  AlignLeft, AlignCenter, AlignRight,
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/components/ui/use-toast";

interface ImageStyles {
  width?: string;
  widthUnit?: string;
  height?: string;
  alignment?: string;
}

interface ImageContent {
  url?: string;
  altText?: string;
}

interface ImageBlock {
  styles?: ImageStyles;
  content?: ImageContent;
}

interface ImageElementProps {
  block: ImageBlock;
  onChange: (updates: Partial<ImageBlock>) => void;
  onDelete: () => void;
  dragHandleProps?: Record<string, any>;
}

export default function ImageElement({ block, onChange, onDelete, dragHandleProps }: ImageElementProps) {
  const { toast } = useToast();
  const [uploading, setUploading] = useState(false);
  const styles = block.styles || {};
  const content = block.content || {};

  const width = styles.width || "100";
  const widthUnit = styles.widthUnit || "%";
  const height = styles.height || "auto";
  const alignment = styles.alignment || "center";
  const imageUrl = content.url || "";
  const altText = content.altText || "";

  const updateStyle = (key: string, value: string) => {
    onChange({ styles: { ...styles, [key]: value } });
  };

  const updateContent = (key: string, value: string) => {
    onChange({ content: { ...content, [key]: value } });
  };

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    try {
      setUploading(true);
      const file = event.target.files?.[0];
      if (!file) return;

      const fileExt = file.name.split(".").pop();
      const fileName = `${Math.random().toString(36).substring(2)}.${fileExt}`;
      const filePath = `form-assets/${fileName}`;

      const { error: uploadError } = await supabase.storage
        .from("company-assets")
        .upload(filePath, file);

      if (uploadError) throw uploadError;

      const {
        data: { publicUrl },
      } = supabase.storage.from("company-assets").getPublicUrl(filePath);

      updateContent("url", publicUrl);
      toast({ title: "Success", description: "Image uploaded successfully" });
    } catch (error) {
      console.error("Error uploading image:", error);
      toast({ variant: "destructive", title: "Error", description: "Failed to upload image." });
    } finally {
      setUploading(false);
    }
  };

  return (
    <div className="group relative bg-card rounded-xl shadow-sm border transition-all duration-200 mb-4 overflow-hidden hover:shadow-md">
      <div className="flex items-center gap-2 p-2 bg-muted/50 border-b">
        <div {...dragHandleProps} className="cursor-move text-muted-foreground hover:text-foreground p-1 rounded hover:bg-muted">
          <GripVertical className="w-4 h-4" />
        </div>
        <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-1">
          <ImageIcon className="w-3 h-3" /> Image
        </span>
        <div className="flex-1" />
        <Button variant="ghost" size="icon" className="h-7 w-7 text-muted-foreground hover:text-destructive" onClick={onDelete}>
          <Trash2 className="w-3.5 h-3.5" />
        </Button>
      </div>

      <div className="p-4 space-y-4">
        {!imageUrl ? (
          <div className="border-2 border-dashed rounded-lg p-6 flex flex-col items-center justify-center bg-muted/30 hover:bg-muted/50 transition-colors">
            <ImageIcon className="w-10 h-10 text-muted-foreground/40 mb-3" />
            <div className="text-center space-y-2">
              <p className="text-sm text-muted-foreground">Upload an image or enter URL</p>
              <div className="flex gap-2 justify-center">
                <div className="relative">
                  <input
                    type="file"
                    accept="image/*"
                    className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                    onChange={handleFileUpload}
                    disabled={uploading}
                  />
                  <Button size="sm" variant="secondary" disabled={uploading}>
                    {uploading ? "Uploading..." : <><Upload className="w-3.5 h-3.5 mr-2" /> Choose File</>}
                  </Button>
                </div>
              </div>
              <div className="relative max-w-xs mx-auto mt-2">
                <Input
                  placeholder="Or paste image URL..."
                  className="text-xs h-8"
                  value={imageUrl}
                  onChange={(e) => updateContent("url", e.target.value)}
                />
              </div>
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="flex gap-4 items-start">
              <div className="w-32 h-32 bg-muted rounded border flex items-center justify-center overflow-hidden shrink-0 relative group/img">
                <img src={imageUrl} alt={altText} className="w-full h-full object-cover" />
                <div className="absolute inset-0 bg-foreground/40 opacity-0 group-hover/img:opacity-100 transition-opacity flex items-center justify-center">
                  <Button variant="secondary" size="sm" className="h-7 text-xs" onClick={() => updateContent("url", "")}>
                    Change
                  </Button>
                </div>
              </div>

              <div className="flex-1 space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-1">
                    <Label className="text-xs">Width</Label>
                    <div className="flex gap-2">
                      <Input type="number" className="h-8 text-xs" value={width} onChange={(e) => updateStyle("width", e.target.value)} />
                      <select
                        className="h-8 text-xs border rounded bg-transparent px-2"
                        value={widthUnit}
                        onChange={(e) => updateStyle("widthUnit", e.target.value)}
                      >
                        <option value="%">%</option>
                        <option value="px">px</option>
                      </select>
                    </div>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs">Height (px)</Label>
                    <Input type="text" className="h-8 text-xs" value={height} onChange={(e) => updateStyle("height", e.target.value)} placeholder="auto" />
                  </div>
                </div>

                <div className="space-y-1">
                  <Label className="text-xs">Alt Text</Label>
                  <Input className="h-8 text-xs" value={altText} onChange={(e) => updateContent("altText", e.target.value)} placeholder="Description for accessibility" />
                </div>

                <div className="space-y-1">
                  <Label className="text-xs">Alignment</Label>
                  <div className="flex bg-muted rounded p-1 w-fit">
                    {(["left", "center", "right"] as const).map((align) => (
                      <Button
                        key={align}
                        variant={alignment === align ? "default" : "ghost"}
                        size="sm"
                        className="h-7 w-8 px-0"
                        onClick={() => updateStyle("alignment", align)}
                      >
                        {align === "left" && <AlignLeft className="w-3.5 h-3.5" />}
                        {align === "center" && <AlignCenter className="w-3.5 h-3.5" />}
                        {align === "right" && <AlignRight className="w-3.5 h-3.5" />}
                      </Button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            {/* Preview */}
            <div className="mt-4 pt-4 border-t">
              <Label className="text-[10px] text-muted-foreground uppercase tracking-wider mb-2 block">Preview</Label>
              <div className="bg-muted/50 p-4 rounded border border-dashed">
                <div style={{ textAlign: alignment as any }}>
                  <img
                    src={imageUrl}
                    alt={altText}
                    style={{
                      width: widthUnit === "%" ? `${width}%` : `${width}px`,
                      height: height === "auto" ? "auto" : `${height}px`,
                      maxWidth: "100%",
                      display: "inline-block",
                    }}
                  />
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
