import { useState, useEffect } from "react";
import { X } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

interface Creative {
  id: string;
  name: string;
  thumbnail_url?: string | null;
}

interface CreativeSelectDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  creatives: Creative[];
  onSelect: (creative: Creative) => void;
  onClear: (() => void) | null;
  currentCreativeId: string | null | undefined;
}

export function CreativeSelectDialog({
  open,
  onOpenChange,
  creatives,
  onSelect,
  onClear,
  currentCreativeId,
}: CreativeSelectDialogProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Выберите креатив</DialogTitle>
        </DialogHeader>
        {creatives.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            Нет доступных креативов
          </div>
        ) : (
          <div className="space-y-2">
            {creatives.map((creative) => (
              <div
                key={creative.id}
                className={cn(
                  "flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors",
                  currentCreativeId === creative.id
                    ? "border-primary bg-primary/5"
                    : "hover:bg-muted"
                )}
                onClick={() => {
                  onSelect(creative);
                  onOpenChange(false);
                }}
              >
                <div className="w-12 h-12 rounded bg-muted flex items-center justify-center overflow-hidden shrink-0">
                  {creative.thumbnail_url ? (
                    <img
                      src={creative.thumbnail_url}
                      alt={creative.name}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <span className="text-xs">📷</span>
                  )}
                </div>
                <span className="text-sm font-medium truncate">{creative.name}</span>
              </div>
            ))}
          </div>
        )}
        {currentCreativeId && onClear && (
          <div className="pt-4 border-t mt-4">
            <Button
              variant="outline"
              className="w-full"
              onClick={() => {
                onClear();
                onOpenChange(false);
              }}
            >
              Отменить выбор креатива
            </Button>
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}

