import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import {
  ChevronDown,
  ChevronUp,
  Heading as HeadingIcon,
  Image as ImageIcon,
  Link as LinkIcon,
  Minus,
  Plus,
  Text,
  Trash2,
  Megaphone,
  Images,
} from "lucide-react";
import {
  ALL_BLOCK_TYPES,
  BLOCK_LABELS,
  ContentBlock,
  newBlock,
  CarouselImage,
} from "./contentBlockTypes";

interface Props {
  value: ContentBlock[];
  onChange: (blocks: ContentBlock[]) => void;
  /** "main" gives full editor; "sidebar" hides Image to keep things tidy */
  variant?: "main" | "sidebar";
}

const ICONS: Record<ContentBlock["type"], any> = {
  heading: HeadingIcon,
  paragraph: Text,
  image: ImageIcon,
  link: LinkIcon,
  divider: Minus,
  callout: Megaphone,
  carousel: Images,
};

export default function ContentBlocksEditor({ value, onChange, variant = "main" }: Props) {
  const blocks = Array.isArray(value) ? value : [];

  const update = (id: string, patch: Partial<ContentBlock>) => {
    onChange(blocks.map((b) => (b.id === id ? ({ ...b, ...patch } as ContentBlock) : b)));
  };
  const remove = (id: string) => onChange(blocks.filter((b) => b.id !== id));
  const move = (id: string, dir: -1 | 1) => {
    const idx = blocks.findIndex((b) => b.id === id);
    if (idx < 0) return;
    const target = idx + dir;
    if (target < 0 || target >= blocks.length) return;
    const next = blocks.slice();
    [next[idx], next[target]] = [next[target], next[idx]];
    onChange(next);
  };
  const add = (type: ContentBlock["type"]) => onChange([...blocks, newBlock(type)]);

  const types = ALL_BLOCK_TYPES.filter((t) => (variant === "sidebar" ? t !== "image" : true));

  return (
    <div className="space-y-3">
      {blocks.length === 0 ? (
        <p className="text-xs text-muted-foreground">
          No content yet. Use the buttons below to add blocks.
        </p>
      ) : (
        <div className="space-y-2">
          {blocks.map((block) => {
            const Icon = ICONS[block.type];
            return (
              <Card key={block.id} className="p-3 space-y-2">
                <div className="flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
                    <Icon className="h-3.5 w-3.5" />
                    {BLOCK_LABELS[block.type]}
                  </div>
                  <div className="flex items-center gap-1">
                    <Button type="button" size="sm" variant="ghost" className="h-7 w-7 p-0" onClick={() => move(block.id, -1)}>
                      <ChevronUp className="h-3.5 w-3.5" />
                    </Button>
                    <Button type="button" size="sm" variant="ghost" className="h-7 w-7 p-0" onClick={() => move(block.id, 1)}>
                      <ChevronDown className="h-3.5 w-3.5" />
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                      onClick={() => remove(block.id)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                </div>

                {block.type === "heading" && (
                  <div className="space-y-2">
                    <Input
                      value={block.text}
                      onChange={(e) => update(block.id, { text: e.target.value })}
                      placeholder="Heading text"
                    />
                    <div className="flex gap-2">
                      {[2, 3, 4].map((lvl) => (
                        <Button
                          key={lvl}
                          type="button"
                          size="sm"
                          variant={(block.level ?? 3) === lvl ? "default" : "outline"}
                          onClick={() => update(block.id, { level: lvl as 2 | 3 | 4 })}
                        >
                          H{lvl}
                        </Button>
                      ))}
                    </div>
                  </div>
                )}

                {block.type === "paragraph" && (
                  <Textarea
                    value={block.text}
                    onChange={(e) => update(block.id, { text: e.target.value })}
                    placeholder="Write your content here..."
                    rows={4}
                  />
                )}

                {block.type === "image" && (
                  <div className="space-y-2">
                    <div className="space-y-1">
                      <Label className="text-xs">Image URL</Label>
                      <Input
                        value={block.url}
                        onChange={(e) => update(block.id, { url: e.target.value })}
                        placeholder="https://..."
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-2">
                      <div className="space-y-1">
                        <Label className="text-xs">Alt text</Label>
                        <Input
                          value={block.alt || ""}
                          onChange={(e) => update(block.id, { alt: e.target.value })}
                          placeholder="Describe the image"
                        />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs">Caption</Label>
                        <Input
                          value={block.caption || ""}
                          onChange={(e) => update(block.id, { caption: e.target.value })}
                          placeholder="Optional caption"
                        />
                      </div>
                    </div>
                  </div>
                )}

                {block.type === "link" && (
                  <div className="grid grid-cols-2 gap-2">
                    <div className="space-y-1">
                      <Label className="text-xs">Label</Label>
                      <Input
                        value={block.label}
                        onChange={(e) => update(block.id, { label: e.target.value })}
                      />
                    </div>
                    <div className="space-y-1">
                      <Label className="text-xs">URL</Label>
                      <Input
                        value={block.url}
                        onChange={(e) => update(block.id, { url: e.target.value })}
                        placeholder="https://..."
                      />
                    </div>
                  </div>
                )}

                {block.type === "callout" && (
                  <div className="space-y-2">
                    <Input
                      value={block.title || ""}
                      onChange={(e) => update(block.id, { title: e.target.value })}
                      placeholder="Title (optional)"
                    />
                    <Textarea
                      value={block.text}
                      onChange={(e) => update(block.id, { text: e.target.value })}
                      placeholder="Callout content..."
                      rows={3}
                    />
                  </div>
                )}

                {block.type === "carousel" && (
                  <div className="space-y-2">
                    {(block.images || []).length === 0 ? (
                      <p className="text-xs text-muted-foreground">No photos yet. Add one below.</p>
                    ) : (
                      <div className="space-y-2">
                        {block.images.map((img, idx) => {
                          const updateImg = (patch: Partial<CarouselImage>) => {
                            const next = block.images.slice();
                            next[idx] = { ...next[idx], ...patch };
                            update(block.id, { images: next });
                          };
                          const removeImg = () => {
                            const next = block.images.slice();
                            next.splice(idx, 1);
                            update(block.id, { images: next });
                          };
                          const moveImg = (dir: -1 | 1) => {
                            const target = idx + dir;
                            if (target < 0 || target >= block.images.length) return;
                            const next = block.images.slice();
                            [next[idx], next[target]] = [next[target], next[idx]];
                            update(block.id, { images: next });
                          };
                          return (
                            <div key={idx} className="rounded-md border p-2 space-y-2 bg-muted/30">
                              <div className="flex items-center justify-between">
                                <span className="text-xs font-medium text-muted-foreground">Photo {idx + 1}</span>
                                <div className="flex items-center gap-1">
                                  <Button type="button" size="sm" variant="ghost" className="h-6 w-6 p-0" onClick={() => moveImg(-1)}>
                                    <ChevronUp className="h-3 w-3" />
                                  </Button>
                                  <Button type="button" size="sm" variant="ghost" className="h-6 w-6 p-0" onClick={() => moveImg(1)}>
                                    <ChevronDown className="h-3 w-3" />
                                  </Button>
                                  <Button type="button" size="sm" variant="ghost" className="h-6 w-6 p-0 text-destructive hover:text-destructive" onClick={removeImg}>
                                    <Trash2 className="h-3 w-3" />
                                  </Button>
                                </div>
                              </div>
                              <Input
                                value={img.url}
                                onChange={(e) => updateImg({ url: e.target.value })}
                                placeholder="Image URL (https://...)"
                              />
                              <div className="grid grid-cols-2 gap-2">
                                <Input
                                  value={img.alt || ""}
                                  onChange={(e) => updateImg({ alt: e.target.value })}
                                  placeholder="Alt text"
                                />
                                <Input
                                  value={img.caption || ""}
                                  onChange={(e) => updateImg({ caption: e.target.value })}
                                  placeholder="Caption (optional)"
                                />
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                    <div className="flex items-center justify-between gap-2">
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        onClick={() => update(block.id, { images: [...(block.images || []), { url: "", alt: "" }] })}
                        className="gap-1.5"
                      >
                        <Plus className="h-3.5 w-3.5" />
                        Add photo
                      </Button>
                      <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
                        <input
                          type="checkbox"
                          checked={!!block.autoplay}
                          onChange={(e) => update(block.id, { autoplay: e.target.checked })}
                        />
                        Autoplay
                      </label>
                    </div>
                  </div>
                )}

                {block.type === "divider" && (
                  <p className="text-xs text-muted-foreground">A horizontal divider line.</p>
                )}
              </Card>
            );
          })}
        </div>
      )}

      <div className="flex flex-wrap gap-2 pt-1">
        {types.map((t) => {
          const Icon = ICONS[t];
          return (
            <Button key={t} type="button" size="sm" variant="outline" onClick={() => add(t)} className="gap-1.5">
              <Plus className="h-3.5 w-3.5" />
              <Icon className="h-3.5 w-3.5" />
              {BLOCK_LABELS[t]}
            </Button>
          );
        })}
      </div>
    </div>
  );
}
