import { useState, useCallback } from 'react';
import DOMPurify from 'dompurify';
import { useToast } from '@/hooks/use-toast';

export function useHtmlImport() {
  const [sanitizedHtml, setSanitizedHtml] = useState('');
  const [rawHtml, setRawHtml] = useState('');
  const [fileMetadata, setFileMetadata] = useState(null);
  const [error, setError] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);
  const { toast } = useToast();

  const sanitizeContent = useCallback((content) => {
    try {
      const clean = DOMPurify.sanitize(content, {
        ADD_TAGS: ['style', 'iframe', 'img', 'table', 'tbody', 'tr', 'td', 'th', 'thead', 'tfoot', 'col', 'colgroup'],
        ADD_ATTR: ['style', 'class', 'id', 'width', 'height', 'align', 'valign', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'src', 'href', 'target'],
        WHOLE_DOCUMENT: false,
        FORCE_BODY: false,
      });
      return clean;
    } catch (err) {
      console.error("Sanitization error:", err);
      return "";
    }
  }, []);

  const processHtmlString = useCallback((htmlString) => {
    setIsProcessing(true);
    setError(null);
    if (!htmlString || htmlString.trim() === '') {
      setRawHtml('');
      setSanitizedHtml('');
      setIsProcessing(false);
      return;
    }
    try {
      setRawHtml(htmlString);
      const clean = sanitizeContent(htmlString);
      setSanitizedHtml(clean);
    } catch (err) {
      setError("Failed to process HTML content");
      toast({ variant: "destructive", title: "Processing Error", description: "Could not process HTML string." });
    } finally {
      setIsProcessing(false);
    }
  }, [sanitizeContent, toast]);

  const processFile = useCallback(async (file) => {
    setIsProcessing(true);
    setError(null);
    if (!file) { setError("No file selected"); setIsProcessing(false); return; }

    const MAX_SIZE = 5 * 1024 * 1024;
    if (file.size > MAX_SIZE) {
      const msg = `File is too large (${(file.size / 1024 / 1024).toFixed(2)}MB). Max size is 5MB.`;
      setError(msg);
      toast({ variant: "destructive", title: "File Too Large", description: msg });
      setIsProcessing(false);
      return;
    }

    const validExtensions = ['html', 'htm', 'txt'];
    const extension = file.name.split('.').pop().toLowerCase();
    if (!validExtensions.includes(extension)) {
      const msg = "Invalid file type. Please upload .html or .txt files.";
      setError(msg);
      toast({ variant: "destructive", title: "Invalid File", description: msg });
      setIsProcessing(false);
      return;
    }

    try {
      const text = await file.text();
      setRawHtml(text);
      const clean = sanitizeContent(text);
      setSanitizedHtml(clean);
      setFileMetadata({ name: file.name, size: file.size, type: file.type, lastModified: file.lastModified });
      toast({ title: "File Processed", description: `Successfully loaded ${file.name}` });
    } catch (err) {
      console.error("File reading error:", err);
      setError("Failed to read file content");
      toast({ variant: "destructive", title: "Read Error", description: "Could not read the file content." });
    } finally {
      setIsProcessing(false);
    }
  }, [sanitizeContent, toast]);

  const clearContent = useCallback(() => {
    setRawHtml('');
    setSanitizedHtml('');
    setFileMetadata(null);
    setError(null);
  }, []);

  return { rawHtml, sanitizedHtml, fileMetadata, error, isProcessing, processHtmlString, processFile, clearContent };
}
