import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AlertCircle } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/lib/supabase";
import { useShop } from "@/components/context/ShopContext";
import { useTranslation } from 'react-i18next';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Placeholder from '@tiptap/extension-placeholder';
import TurndownService from 'turndown';

interface CustomContentTextEntryProps {
  onSuccess: () => void;
}

// URL validation regex (matches http://, https://, www.)
const URL_REGEX = /https?:\/\/[^\s]+|www\.[^\s]+/gi;

// Image tag regex (matches img tags, markdown images, and common image URLs)
const IMAGE_REGEX = /<img[^>]*>|\!\[.*?\]\(.*?\)|https?:\/\/[^\s]+\.(jpg|jpeg|png|gif|bmp|svg|webp)/gi;

// Initialize Turndown service for HTML to Markdown conversion
const turndownService = new TurndownService({
  headingStyle: 'atx',
  codeBlockStyle: 'fenced',
});

// Remove image tags from markdown
turndownService.remove('img');

// Clean up text: remove excessive whitespace, newlines, tabs
const cleanupText = (text: string): string => {
  return text
    .replace(/\t/g, ' ')              // Replace tabs with spaces
    .replace(/[ ]+/g, ' ')            // Replace multiple spaces with single space
    .replace(/\n{3,}/g, '\n\n')       // Replace 3+ newlines with 2 newlines
    .replace(/^\s+|\s+$/gm, '')       // Trim whitespace from each line
    .trim();                           // Trim overall
};

export function CustomContentTextEntry({ onSuccess }: CustomContentTextEntryProps) {
  const { t } = useTranslation();
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [format, setFormat] = useState<'plain' | 'markdown' | 'wysiwyg'>('plain');
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [editorHasContent, setEditorHasContent] = useState(false);
  const { toast } = useToast();
  const { selectedShop } = useShop();

  // Initialize TipTap editor for WYSIWYG mode
  const editor = useEditor({
    extensions: [
      StarterKit,
      Placeholder.configure({
        placeholder: t('customContent.textEntry.wysiwygPlaceholder'),
      }),
    ],
    content: '',
    editorProps: {
      attributes: {
        class: 'prose prose-invert max-w-full min-h-[288px] p-4 focus:outline-none bg-slate-900 border border-slate-600 rounded-md text-white break-words overflow-wrap-anywhere',
      },
    },
    onUpdate: ({ editor }) => {
      // Update state when editor content changes
      const text = editor.getText();
      const hasText = text.trim().length > 0;
      setEditorHasContent(hasText);
    },
  });

  // Validate content doesn't contain URLs or images
  const validateContent = (text: string): { isValid: boolean; error?: string } => {
    if (URL_REGEX.test(text)) {
      return { isValid: false, error: t('customContent.textEntry.errorContainsUrl') };
    }
    if (IMAGE_REGEX.test(text)) {
      return { isValid: false, error: t('customContent.textEntry.errorContainsImage') };
    }
    return { isValid: true };
  };

  // Get content based on current format
  const getCurrentContent = (): string => {
    let rawContent = '';

    if (format === 'wysiwyg' && editor) {
      const html = editor.getHTML();
      // Convert HTML to Markdown
      rawContent = turndownService.turndown(html);
    } else {
      rawContent = content;
    }

    // Clean up the text
    return cleanupText(rawContent);
  };

  // Check if content has any text (computed value, not a function)
  const hasContent = format === 'wysiwyg'
    ? editorHasContent
    : content.trim().length > 0;

  const handleSave = async () => {
    // Get content based on format (already cleaned up)
    const finalContent = getCurrentContent();

    if (!title.trim() || !finalContent.trim()) {
      setError(t('customContent.textEntry.errorRequired'));
      return;
    }

    // Validate no URLs or images
    const validation = validateContent(finalContent);
    if (!validation.isValid) {
      setError(validation.error || t('customContent.textEntry.errorInvalidContent'));
      return;
    }

    if (finalContent.length > 50000) {
      setError(t('customContent.textEntry.errorMaxLength'));
      return;
    }

    if (!selectedShop) {
      setError(t('customContent.textEntry.errorSelectShop'));
      return;
    }

    setSaving(true);
    setError(null);

    try {
      // Get auth token
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error("Not authenticated");
      }

      // Create entry via Edge Function
      const response = await fetch(
        `${import.meta.env.VITE_API_URL}/custom-content-create`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${session.access_token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            title: title.trim(),
            content_text: finalContent.trim(),
            store_id: selectedShop.id,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || t('customContent.textEntry.errorTitle'));
      }

      toast({
        title: t('customContent.textEntry.successTitle'),
        description: t('customContent.textEntry.successDescription', { title }),
      });

      onSuccess();
    } catch (err: any) {
      console.error("Create error:", err);
      setError(err.message || t('customContent.textEntry.errorTitle'));
      toast({
        title: t('customContent.textEntry.errorTitle'),
        description: err.message || t('customContent.textEntry.errorTitle'),
        variant: "destructive",
      });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="space-y-4">
      <div>
        <h2 className="text-lg font-semibold text-white">{t('customContent.textEntry.title')}</h2>
        <p className="text-sm text-slate-400">
          {t('customContent.textEntry.description')}
        </p>
      </div>

      {/* Title Input */}
      <div className="space-y-2">
        <Label htmlFor="entry-title" className="text-slate-300">{t('customContent.textEntry.titleLabel')} *</Label>
        <Input
          id="entry-title"
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          placeholder={t('customContent.textEntry.titlePlaceholder')}
          disabled={saving}
          className="bg-slate-900 border-slate-600 text-white placeholder:text-slate-500"
        />
      </div>

      {/* Content Input with Format Tabs */}
      <div className="space-y-2">
        <Label className="text-slate-300">{t('customContent.textEntry.contentLabel')} *</Label>

        <Tabs value={format} onValueChange={(value) => setFormat(value as 'plain' | 'markdown' | 'wysiwyg')} className="w-full">
          <TabsList className="grid w-full grid-cols-3 bg-slate-700">
            <TabsTrigger value="plain" className="data-[state=active]:bg-slate-900">
              {t('customContent.textEntry.formatPlain')}
            </TabsTrigger>
            <TabsTrigger value="markdown" className="data-[state=active]:bg-slate-900">
              {t('customContent.textEntry.formatMarkdown')}
            </TabsTrigger>
            <TabsTrigger value="wysiwyg" className="data-[state=active]:bg-slate-900">
              {t('customContent.textEntry.formatWysiwyg')}
            </TabsTrigger>
          </TabsList>

          <TabsContent value="plain" className="mt-2">
            <Textarea
              id="entry-content-plain"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder={t('customContent.textEntry.contentPlaceholder')}
              rows={12}
              disabled={saving}
              className="resize-none bg-slate-900 border-slate-600 text-white placeholder:text-slate-500"
            />
          </TabsContent>

          <TabsContent value="markdown" className="mt-2">
            <Textarea
              id="entry-content-markdown"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder={t('customContent.textEntry.markdownPlaceholder')}
              rows={12}
              disabled={saving}
              className="resize-none bg-slate-900 border-slate-600 text-white placeholder:text-slate-500 font-mono"
            />
          </TabsContent>

          <TabsContent value="wysiwyg" className="mt-2" forceMount>
            <div className={format === 'wysiwyg' ? 'block' : 'hidden'}>
              <div className="min-h-[288px] max-h-[400px] overflow-y-auto">
                <EditorContent editor={editor} />
              </div>
            </div>
          </TabsContent>
        </Tabs>

        <p className="text-xs text-slate-500 text-right">
          {t('customContent.textEntry.characterCount', {
            count: (title.length + (format === 'wysiwyg' && editor ? editor.getText().length : content.length)).toLocaleString()
          })}
        </p>
        <p className="text-xs text-slate-400">
          {t('customContent.textEntry.validationNote')}
        </p>
      </div>

      {/* Error Alert */}
      {error && (
        <Alert variant="destructive" className="bg-red-900/20 border-red-800">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription className="text-red-200">{error}</AlertDescription>
        </Alert>
      )}

      {/* Action Buttons */}
      <div className="flex justify-end gap-2">
        <Button
          variant="outline"
          onClick={() => onSuccess()}
          disabled={saving}
          className="bg-slate-700 border-slate-600 text-white hover:bg-slate-600"
        >
          {t('customContent.textEntry.cancel')}
        </Button>
        <Button
          onClick={handleSave}
          disabled={!title.trim() || !hasContent || saving}
          className="bg-cyan-500 hover:bg-cyan-600 text-white"
        >
          {saving ? t('customContent.textEntry.saving') : t('customContent.textEntry.save')}
        </Button>
      </div>
    </div>
  );
}
