'use client';

import { useState, useEffect, useRef } from 'react';
import { Box, Text, Title, Stack, Group, Button } from '@tidbcloud/uikit';
import { Artifact } from '@/lib/workspace';
import { useTranslation } from '@/lib/i18n';

interface NoteModalProps {
  opened: boolean;
  onClose: () => void;
  /** When editing an existing note, pass the artifact */
  note?: Artifact | null;
  onSave: (title: string, content: string) => void;
}

export default function NoteModal({ opened, onClose, note, onSave }: NoteModalProps) {
  const { t } = useTranslation();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const titleRef = useRef<HTMLInputElement>(null);

  const isEditing = !!note;

  useEffect(() => {
    if (opened) {
      if (note) {
        setTitle(note.title || '');
        setContent((note.data?.content as string) || '');
      } else {
        setTitle('');
        setContent('');
      }
      // Auto-focus title
      setTimeout(() => titleRef.current?.focus(), 100);
    }
  }, [opened, note]);

  if (!opened) return null;

  const handleSave = () => {
    if (!title.trim() && !content.trim()) return;
    onSave(title.trim() || t('studio.note.untitled'), content.trim());
    handleClose();
  };

  const handleClose = () => {
    setTitle('');
    setContent('');
    onClose();
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Escape') {
      handleClose();
    }
    // Cmd/Ctrl + Enter to save
    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
      handleSave();
    }
  };

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={handleClose}
        style={{
          position: 'fixed',
          inset: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          zIndex: 1000,
        }}
      />

      {/* Modal */}
      <Box
        p="lg"
        style={{
          position: 'fixed',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: '520px',
          maxWidth: '90vw',
          maxHeight: '80vh',
          backgroundColor: '#fff',
          borderRadius: '12px',
          boxShadow: '0 20px 60px rgba(0, 0, 0, 0.15)',
          zIndex: 1001,
          display: 'flex',
          flexDirection: 'column',
        }}
        onKeyDown={handleKeyDown}
      >
        <Stack gap="md" style={{ flex: 1 }}>
          {/* Header */}
          <Group justify="space-between" align="center">
            <Group gap="xs" align="center">
              <span style={{ fontSize: '18px' }}>🗒️</span>
              <Title order={5}>{isEditing ? t('studio.note.editTitle') : t('studio.note.newTitle')}</Title>
            </Group>
            <button
              onClick={handleClose}
              style={{
                background: 'none',
                border: 'none',
                cursor: 'pointer',
                fontSize: '18px',
                color: '#6b7280',
                padding: '4px',
              }}
            >
              ✕
            </button>
          </Group>

          {/* Title input */}
          <div>
            <Text size="sm" fw={500} c="carbon.7" mb={4}>{t('studio.note.titleLabel')}</Text>
            <input
              ref={titleRef}
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder={t('studio.note.titlePlaceholder')}
              style={{
                width: '100%',
                padding: '8px 12px',
                border: '1px solid #d1d5db',
                borderRadius: '8px',
                fontSize: '14px',
                outline: 'none',
                transition: 'border-color 0.15s',
                boxSizing: 'border-box',
              }}
              onFocus={(e) => (e.target.style.borderColor = '#3b82f6')}
              onBlur={(e) => (e.target.style.borderColor = '#d1d5db')}
            />
          </div>

          {/* Content textarea */}
          <div style={{ flex: 1 }}>
            <Text size="sm" fw={500} c="carbon.7" mb={4}>{t('studio.note.contentLabel')}</Text>
            <textarea
              value={content}
              onChange={(e) => setContent(e.target.value)}
              placeholder={t('studio.note.contentPlaceholder')}
              style={{
                width: '100%',
                minHeight: '200px',
                maxHeight: '400px',
                padding: '10px 12px',
                border: '1px solid #d1d5db',
                borderRadius: '8px',
                fontSize: '14px',
                fontFamily: 'inherit',
                outline: 'none',
                resize: 'vertical',
                transition: 'border-color 0.15s',
                boxSizing: 'border-box',
                lineHeight: '1.6',
              }}
              onFocus={(e) => (e.target.style.borderColor = '#3b82f6')}
              onBlur={(e) => (e.target.style.borderColor = '#d1d5db')}
            />
          </div>

          {/* Footer */}
          <Group justify="space-between" align="center">
            <Text size="xs" c="carbon.4">
              {isEditing ? t('studio.note.editHint') : t('studio.note.saveHint')}
            </Text>
            <Group gap="xs">
              <Button variant="subtle" color="gray" size="xs" onClick={handleClose}>
                {t('studio.note.cancel')}
              </Button>
              <Button
                size="xs"
                onClick={handleSave}
                disabled={!title.trim() && !content.trim()}
              >
                {isEditing ? t('studio.note.saveChanges') : t('studio.note.create')}
              </Button>
            </Group>
          </Group>
        </Stack>
      </Box>
    </>
  );
}
