"use client";

import { useState } from "react";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { ExternalLink } from "lucide-react";

interface TelegramPostPreviewProps {
  text: string;
  mediaItems?: Array<{ media_type: string; media_file_id: string }>;
  buttons?: Array<{ text: string; url: string }>;
  inviteLinkPreview?: string;
}

export function TelegramPostPreview({
  text,
  mediaItems,
  buttons,
  inviteLinkPreview = "https://t.me/+AbCdEfGhIjK",
}: TelegramPostPreviewProps) {
  const [hoveredLink, setHoveredLink] = useState<string | null>(null);

  const renderTextWithLinks = () => {
    const result: React.ReactNode[] = [];
    let lastIndex = 0;
    const patterns = [
      { regex: /<a\s+class=["']tg-link["']>([^<]*)<\/a>/gi, type: 'tg-link' },
      { regex: /\{invite_link\}/gi, type: 'single' },
    ];

    const matches: { start: number; end: number; type: string; text?: string }[] = [];

    patterns.forEach(({ regex, type }) => {
      let match;
      while ((match = regex.exec(text)) !== null) {
        matches.push({
          start: match.index!,
          end: match.index! + match[0].length,
          type,
          text: match[1],
        });
      }
    });

    matches.sort((a, b) => a.start - b.start);

    matches.forEach((match) => {
      if (lastIndex < match.start) {
        result.push(<span key={`text-${lastIndex}`}>{text.slice(lastIndex, match.start)}</span>);
      }

      const linkContent = match.type === 'tg-link' && match.text ? match.text : '[ссылка]';

      result.push(
        <TooltipProvider key={`link-${match.start}`}>
          <Tooltip open={hoveredLink === `${match.start}-${match.end}`} onOpenChange={(open) => setHoveredLink(open ? `${match.start}-${match.end}` : null)}>
            <TooltipTrigger asChild>
              <a
                href="#"
                onClick={(e) => e.preventDefault()}
                className="text-primary font-medium underline hover:opacity-80 transition-opacity"
                onMouseEnter={() => setHoveredLink(`${match.start}-${match.end}`)}
                onMouseLeave={() => setHoveredLink(null)}
              >
                {linkContent}
              </a>
            </TooltipTrigger>
            <TooltipContent>
              <div className="space-y-1">
                <p className="text-xs text-muted-foreground">Сюда будет подставлена ссылка на канал:</p>
                <div className="flex items-center gap-2">
                  <ExternalLink className="h-3.5 w-3.5" />
                  <span className="font-mono text-xs">{inviteLinkPreview}</span>
                </div>
              </div>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );

      lastIndex = match.end;
    });

    if (lastIndex < text.length) {
      result.push(<span key={`text-end-${lastIndex}`}>{text.slice(lastIndex)}</span>);
    }

    return result;
  };

  const renderButton = (button: { text: string; url: string }, index: number) => {
    const hasInviteLink = button.url === '{{invite_link}}';

    return (
      <TooltipProvider key={index}>
        <Tooltip open={hoveredLink === `button-${index}`} onOpenChange={(open) => setHoveredLink(open ? `button-${index}` : null)}>
          <TooltipTrigger asChild>
            <button
              className={`w-full py-2 text-sm font-medium transition-colors ${
                buttons && buttons.length === 1 ? 'text-primary hover:bg-primary/10 rounded-full' : 'text-primary hover:bg-primary/10 rounded-md'
              }`}
            >
              {button.text}
            </button>
          </TooltipTrigger>
          {hasInviteLink && (
            <TooltipContent>
              <div className="space-y-1">
                <p className="text-xs text-muted-foreground">Сюда будет подставлена ссылка на канал:</p>
                <div className="flex items-center gap-2">
                  <ExternalLink className="h-3.5 w-3.5" />
                  <span className="font-mono text-xs">{inviteLinkPreview}</span>
                </div>
              </div>
            </TooltipContent>
          )}
        </Tooltip>
      </TooltipProvider>
    );
  };

  const getMediaGrid = () => {
    if (!mediaItems || mediaItems.length === 0) return null;
    const count = mediaItems.length;

    if (count === 1) {
      return (
        <div className="rounded-lg overflow-hidden bg-muted h-64 flex items-center justify-center">
          <MediaPreview media={mediaItems[0]} />
        </div>
      );
    }

    if (count === 2) {
      return (
        <div className="grid grid-cols-2 gap-0.5 rounded-lg overflow-hidden">
          {mediaItems.map((media, index) => (
            <div key={index} className="aspect-square bg-muted flex items-center justify-center">
              <MediaPreview media={media} />
            </div>
          ))}
        </div>
      );
    }

    if (count === 3) {
      return (
        <div className="grid grid-cols-2 grid-rows-2 gap-0.5 rounded-lg overflow-hidden">
          <div className="row-span-2 bg-muted flex items-center justify-center">
            <MediaPreview media={mediaItems[0]} />
          </div>
          <div className="bg-muted flex items-center justify-center">
            <MediaPreview media={mediaItems[1]} />
          </div>
          <div className="bg-muted flex items-center justify-center">
            <MediaPreview media={mediaItems[2]} />
          </div>
        </div>
      );
    }

    if (count >= 4) {
      return (
        <div className="grid grid-cols-2 grid-rows-2 gap-0.5 rounded-lg overflow-hidden">
          {mediaItems.slice(0, 4).map((media, index) => (
            <div key={index} className="aspect-square bg-muted flex items-center justify-center">
              <MediaPreview media={media} />
            </div>
          ))}
          {mediaItems.length > 4 && (
            <div className="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
              +{mediaItems.length - 4}
            </div>
          )}
        </div>
      );
    }

    return null;
  };

  return (
    <div className="w-full max-w-[384px] mx-auto bg-background rounded-xl overflow-hidden border shadow-sm">
      <div className="p-3 space-y-2">
        {mediaItems && mediaItems.length > 0 && (
          <div className="relative">
            {getMediaGrid()}
          </div>
        )}

        <div className="whitespace-pre-wrap text-sm leading-relaxed px-1">
          {renderTextWithLinks()}
        </div>
      </div>

      {buttons && buttons.length > 0 && (
        <div className="border-t px-3 pb-3 pt-2">
          {buttons.map((button, index) => renderButton(button, index))}
        </div>
      )}
    </div>
  );
}

function MediaPreview({ media }: { media: { media_type: string; media_file_id: string } }) {
  return (
    <div className="flex flex-col items-center gap-2">
      {media.media_type === "photo" && (
        <span className="text-4xl">📷</span>
      )}
      {media.media_type === "video" && (
        <span className="text-4xl">🎬</span>
      )}
      {media.media_type === "animation" && (
        <span className="text-4xl">🎞️</span>
      )}
      <span className="text-xs text-muted-foreground font-mono">
        {media.media_file_id.slice(0, 12)}...
      </span>
    </div>
  );
}
