'use client';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { EditFormProps } from '@/types/common';
import DOMPurify from 'dompurify';
import { PlayIcon, XCircle } from 'lucide-react';
import { useEffect, useState } from 'react';

export function CodeEditForm({ props, onPropChange }: EditFormProps) {
  const [localCode, setLocalCode] = useState((props.code as string) || '');
  const [error, setError] = useState<string | null>(null);
  const [isDirty, setIsDirty] = useState(false);

  useEffect(() => {
    setLocalCode((props.code as string) || '');
    setIsDirty(false);
    setError(null);
  }, [props.code]);

  const validateHTML = (code: string) => {
    try {
      if (!code.trim()) {
        throw new Error('Code cannot be empty');
      }

      const codeWithoutComments = code.replace(/<!--[\s\S]*?-->/g, '');
      const stack: string[] = [];
      const tagRegex = /<\/?([a-zA-Z0-9]+)(?: [^>]*)?>/g;
      let match;
      let position = 0;

      while ((match = tagRegex.exec(codeWithoutComments)) !== null) {
        const [fullTag, tagName] = match;
        position = match.index;

        const voidElements = [
          'area',
          'base',
          'br',
          'col',
          'embed',
          'hr',
          'img',
          'input',
          'link',
          'meta',
          'param',
          'source',
          'track',
          'wbr',
        ];
        if (voidElements.includes(tagName.toLowerCase())) {
          continue;
        }

        if (fullTag.startsWith('</')) {
          if (stack.length === 0) {
            throw new Error(`Unexpected closing tag </${tagName}> at position ${position}`);
          }
          const lastOpenTag = stack.pop();
          if (lastOpenTag !== tagName) {
            throw new Error(`Mismatched tags: expected </${lastOpenTag}>, found </${tagName}> at position ${position}`);
          }
        } else if (!fullTag.endsWith('/>')) {
          stack.push(tagName);
        }
      }

      if (stack.length > 0) {
        throw new Error(`Unclosed tags: ${stack.join(', ')}`);
      }

      const commonErrors = [
        { regex: /<[^>]*</g, message: 'Nested tag opening brackets < found' },
        { regex: />[^<]*>/g, message: 'Nested tag closing brackets > found' },
        { regex: /\s(href|src)=(?!")/g, message: 'Unquoted attribute values found' },
      ];

      for (const error of commonErrors) {
        const matches = RegExp(error.regex).exec(codeWithoutComments);
        if (matches) {
          throw new Error(error.message);
        }
      }

      const parser = new DOMParser();
      const doc = parser.parseFromString(code, 'text/html');
      const parserError = doc.querySelector('parsererror');
      if (parserError) {
        throw new Error('Invalid HTML structure');
      }

      return true;
    } catch (err) {
      throw new Error(err instanceof Error ? err.message : 'Invalid HTML code');
    }
  };

  const validateAndSanitizeCode = (code: string) => {
    try {
      validateHTML(code);

      const sanitized = DOMPurify.sanitize(code, {
        ADD_TAGS: ['iframe', 'script'],
        FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover'],
        RETURN_DOM_FRAGMENT: true,
      });

      if (!sanitized.textContent && !sanitized.children.length) {
        throw new Error('Content was completely sanitized due to security concerns');
      }

      return DOMPurify.sanitize(code, {
        ADD_TAGS: ['iframe', 'script'],
        FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover'],
      });
    } catch (err) {
      throw new Error(err instanceof Error ? err.message : 'Invalid HTML code');
    }
  };

  const handleCodeChange = (value: string) => {
    setLocalCode(value);
    setIsDirty(true);
    setError(null);
  };

  const handleExecute = () => {
    try {
      const sanitizedCode = validateAndSanitizeCode(localCode);
      onPropChange('code', sanitizedCode);
      setIsDirty(false);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Invalid HTML code');
    }
  };

  return (
    <div className='space-y-4'>
      <div className='space-y-2'>
        <div className='flex items-center justify-between'>
          <Label>HTML Code</Label>
          <Button
            onClick={handleExecute}
            disabled={!isDirty}
            className='flex items-center gap-2'
            variant={isDirty ? 'default' : 'ghost'}
          >
            <PlayIcon className='w-4 h-4' />
            Execute Code
          </Button>
        </div>
        <Textarea
          value={localCode}
          onChange={(e) => handleCodeChange(e.target.value)}
          className={`min-h-[500px] font-mono text-sm bg-neutral-800 border-neutral-600 ${error ? 'border-red-500' : ''}`}
          placeholder='Enter your HTML code here...'
          spellCheck={false}
        />
        {error && (
          <div className='flex items-center gap-2 text-red-500 text-sm mt-2'>
            <XCircle className='w-4 h-4' />
            {error}
          </div>
        )}
      </div>
    </div>
  );
}
