'use client';

import { RiCalendarLine, RiUserLine, RiArrowLeftLine } from '@remixicon/react';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinners';
import { useBlog, useBlogContents, useBlogFaqs } from '../hooks';

interface Props {
  blogId: number;
  onClose?: () => void;
}

function sanitizeHtml(html: string): string {
  if (!html) return '';
  return html
    .replace(/<script[\s\S]*?<\/script>/gi, '')
    .replace(/on\w+\s*=\s*["'][^"']*["']/gi, '')
    .replace(/on\w+\s*=\s*[^\s>]+/gi, '')
    .replace(/javascript\s*:/gi, '');
}

function getImageUrl(image: string | null | undefined): string {
  if (!image) return '';
  if (typeof image !== 'string') return '';
  if (image.startsWith('http')) return image;
  if (image.includes('/')) return `https://sanad.work/${image.replace(/^\//, '')}`;
  return `https://sanad.work/production/storage/blogs/attachments/${image}`;
}

function getYouTubeEmbedUrl(url: string): string | null {
  const match = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]+)/);
  return match ? `https://www.youtube.com/embed/${match[1]}` : null;
}

export default function BlogPreview({ blogId, onClose }: Props) {
  const { data: blog, isLoading: blogLoading } = useBlog(blogId);
  const { data: contents, isLoading: contentsLoading } = useBlogContents(blogId);
  const { data: faqs, isLoading: faqsLoading } = useBlogFaqs(blogId);

  const isLoading = blogLoading || contentsLoading || faqsLoading;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20 text-muted-foreground gap-2">
        <Spinner className="size-5 animate-spin" /> Loading preview...
      </div>
    );
  }

  if (!blog) {
    return (
      <div className="text-center py-12">
        <p className="font-medium">Blog not found</p>
      </div>
    );
  }

  const title = typeof blog.title === 'string' ? blog.title : '';
  const heroImage = getImageUrl(blog.image);
  const createdAt = blog.created_at
    ? new Date(blog.created_at).toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      })
    : '';

  const createdByName = (() => {
    const cb = blog.created_by as unknown as Record<string, unknown>;
    if (!cb) return '';
    const user = cb?.user as Record<string, unknown> | undefined;
    return user?.user_name ? String(user.user_name) : '';
  })();

  return (
    <div className="space-y-4">
      {onClose && (
        <Button variant="ghost" size="sm" onClick={onClose}>
          <RiArrowLeftLine className="size-4 mr-1" />
          Back to Editor
        </Button>
      )}

      <div className="max-w-4xl mx-auto bg-white dark:bg-card rounded-xl shadow-sm border overflow-hidden">
        {heroImage && (
          <div className="w-full h-64 md:h-80 bg-muted overflow-hidden">
            <img
              src={heroImage}
              alt={title}
              className="w-full h-full object-cover"
            />
          </div>
        )}

        <div className="p-6 md:p-10 space-y-8">
          <header className="space-y-4">
            <div className="flex items-center gap-3 text-sm text-muted-foreground">
              {createdAt && (
                <span className="flex items-center gap-1.5">
                  <RiCalendarLine className="size-4" />
                  {createdAt}
                </span>
              )}
              {createdByName && (
                <span className="flex items-center gap-1.5">
                  <RiUserLine className="size-4" />
                  {createdByName}
                </span>
              )}
            </div>

            <h1 className="text-3xl md:text-4xl font-bold leading-tight text-foreground">
              {title}
            </h1>
          </header>

          <hr className="border-border" />

          {contents && contents.length > 0 && (
            <div className="space-y-8">
              {contents.map((section) => {
                const raw = section as unknown as Record<string, unknown>;
                const sectionTitle = String(raw.title ?? '');
                const contentArr = raw.content as Array<Record<string, unknown>> | undefined;
                const contentType = String(raw.content_type ?? 'list');
                const sectionImage = getImageUrl(raw.attachment as string | null);
                const videoUrl = raw.video_url as string | null;
                const externalUrl = raw.url as string | null;

                return (
                  <article key={section.id} className="space-y-3">
                    {sectionTitle && (
                      <h2 className="text-xl md:text-2xl font-semibold text-foreground">
                        {sectionTitle}
                      </h2>
                    )}

                    {contentArr && contentArr.map((block, blockIdx) => {
                      const blockTitle = String(block.title ?? '');
                      const blockDesc = String(block.description ?? '');
                      const blockSubtitle = String(block.subtitle ?? '');
                      const values = (block.values as Array<Record<string, string>>) ?? [];

                      return (
                        <div key={blockIdx} className="space-y-2">
                          {blockTitle && blockTitle !== sectionTitle && (
                            <h3 className="text-lg font-medium text-foreground">{blockTitle}</h3>
                          )}
                          {blockSubtitle && (
                            <p className="text-sm font-medium text-muted-foreground">{blockSubtitle}</p>
                          )}
                          {blockDesc && (
                            <div
                              className="text-base text-muted-foreground leading-relaxed prose prose-sm max-w-none"
                              dangerouslySetInnerHTML={{ __html: sanitizeHtml(blockDesc) }}
                            />
                          )}

                          {values.length > 0 && contentType === 'list' && (
                            <ul className="list-disc list-inside space-y-1.5 text-base text-foreground pl-2">
                              {values.map((v, i) => (
                                <li key={i}>{v.title}</li>
                              ))}
                            </ul>
                          )}

                          {values.length > 0 && contentType === 'table' && (
                            <div className="border rounded-lg overflow-hidden">
                              <table className="w-full text-sm">
                                <tbody>
                                  {values.map((v, i) => (
                                    <tr key={i} className={i % 2 === 0 ? 'bg-muted/30' : ''}>
                                      <td className="px-4 py-2.5">{v.title}</td>
                                    </tr>
                                  ))}
                                </tbody>
                              </table>
                            </div>
                          )}

                          {values.length > 0 && contentType === 'links' && (
                            <div className="space-y-2">
                              {values.map((v, i) => (
                                <div key={i}>
                                  {v.url ? (
                                    <a
                                      href={v.url}
                                      target="_blank"
                                      rel="noopener noreferrer"
                                      className="flex items-center gap-2 text-primary hover:underline"
                                    >
                                      <span className="text-xs">→</span>
                                      <span>{v.title}</span>
                                    </a>
                                  ) : (
                                    <div className="flex items-center gap-2 text-foreground">
                                      <span className="text-xs">→</span>
                                      <span>{v.title}</span>
                                    </div>
                                  )}
                                </div>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}

                    {sectionImage && (
                      <div className="rounded-lg overflow-hidden border mt-4">
                        <img src={sectionImage} alt={sectionTitle} className="w-full max-h-96 object-cover" />
                      </div>
                    )}

                    {videoUrl && (() => {
                      const embedUrl = getYouTubeEmbedUrl(videoUrl);
                      return embedUrl ? (
                        <div className="mt-4 relative w-full" style={{ paddingBottom: '56.25%' }}>
                          <iframe
                            src={embedUrl}
                            className="absolute inset-0 w-full h-full rounded-lg border"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                            allowFullScreen
                          />
                        </div>
                      ) : (
                        <p className="mt-2 text-sm">
                          <a href={videoUrl} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
                            {videoUrl}
                          </a>
                        </p>
                      );
                    })()}

                    {externalUrl && (
                      <p className="mt-2 text-sm">
                        <a href={externalUrl} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">
                          {externalUrl}
                        </a>
                      </p>
                    )}
                  </article>
                );
              })}
            </div>
          )}

          {faqs && faqs.length > 0 && (
            <>
              <hr className="border-border" />
              <div className="space-y-4">
                <h2 className="text-2xl font-semibold text-foreground">
                  Frequently Asked Questions
                </h2>
                <div className="space-y-3">
                  {faqs.map((faq) => (
                    <details
                      key={faq.id}
                      className="group border rounded-lg overflow-hidden"
                    >
                      <summary className="flex items-center justify-between px-5 py-4 cursor-pointer select-none hover:bg-muted/30 transition-colors">
                        <span className="font-medium text-foreground">{String(faq.question ?? '')}</span>
                        <span className="text-muted-foreground transition-transform group-open:rotate-180 ml-4 shrink-0">
                          ▾
                        </span>
                      </summary>
                      <div
                        className="px-5 pb-4 pt-1 text-muted-foreground leading-relaxed border-t prose prose-sm max-w-none"
                        dangerouslySetInnerHTML={{ __html: sanitizeHtml(String(faq.answer ?? '')) }}
                      />
                    </details>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
