import { $, component$, useSignal, useVisibleTask$, NoSerialize } from "@builder.io/qwik";
import { useLocation, useNavigate } from "@builder.io/qwik-city";
import axios from "axios";
import { noSerialize } from "@builder.io/qwik";
// import { PhotoUploadModal } from "~/components/features/diary/UploadImages";
import { getCookie } from "~/utils/cookie";
interface FileInfo {
  name: string;
  size: number;
  type: string;
  lastModified: number;
  url: string;
}
export default component$(() => {
  const content = useSignal('');
  const title = useSignal('');
  const category = useSignal('');
  const selectedImages = useSignal<File[]>([]);
  const textareaRef = useSignal<HTMLTextAreaElement>();
  const nav = useNavigate();
  const location = useLocation();
  const showPhotoUploadModal = useSignal(false);
  const fileInfo = useSignal<FileInfo | null>(null);
  const fileRef = useSignal<NoSerialize<File> | null>(null);
  const error = useSignal('');
  // const fileInputRef = useSignal<HTMLInputElement>();
  
  const handleFileSelect = $(async (selectedFile: File) => {
    if (selectedFile && selectedFile.type.startsWith('image/')) {
      fileInfo.value = {
        name: selectedFile.name,
        size: selectedFile.size,
        type: selectedFile.type,
        lastModified: selectedFile.lastModified,
        url: URL.createObjectURL(selectedFile)
      };
      fileRef.value = noSerialize(selectedFile); 
      error.value = '';
      console.log(fileInfo.value);
    } else {
      error.value = '이미지 파일만 업로드 가능합니다.';
      fileInfo.value = null;
      fileRef.value = null;
    }
  });

  const handleRemoveImage = $((index: number) => {
    selectedImages.value = selectedImages.value.filter((_, i) => i !== index);
  });

  const handleSend = $(async () => {
    try {
      const formData = new FormData();
      formData.append('title', title.value);
      formData.append('content', content.value);
      formData.append('category', category.value);
      
      // Append each image file
      selectedImages.value.forEach((file) => {
        formData.append('file', file);
      });
      
      await axios.post('http://localhost:8000/api/diary', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: `Bearer ${getCookie("access_token")}`,
        },
      });
      
      nav(`/${location.params.username}/diary`);
    } catch (error: any) {
      console.error('Error creating diary:', error);
    }
  });
  useVisibleTask$(({ track }) => {
    track(() => content.value);
    if (textareaRef.value) {
      textareaRef.value.style.height = 'auto';
      textareaRef.value.style.height = `${textareaRef.value.scrollHeight}px`;
    }
  });

  return (
    <div class="p-6">
      <div class="flex justify-between items-center mb-8">
        <h1 class="text-2xl font-bold">일기 쓰기</h1>
      </div>
      <div class="border-b-2 border-text-default flex flex-row justify-between items-center">
        <input 
          bind:value={title}
          type="text" 
          placeholder="제목을 입력해주세요." 
          class="w-full text-2xl font-bold p-2 text-black focus:outline-none"
        />
        <div class="flex gap-3">
          <button onClick$={() => nav(`/${location.params.username}/diary`)}>
            <i class="bi bi-trash-fill text-3xl text-black"></i>
          </button>
          <button 
            class="px-2"
            onClick$={() => showPhotoUploadModal.value = true}
           >
            <i class="bi bi-image-fill text-black text-3xl"></i>
          </button>
          <button onClick$={() => handleSend()}>
            <i class="bi bi-send-fill text-3xl text-black"></i>
          </button>
        </div>
      </div>
      
      {/* Image upload and preview section */}
      <div class="p-4">
        <div class="flex gap-2 overflow-x-auto py-1">
          {selectedImages.value.map((image, index) => (
            <div key={index} class="relative">
              <img 
                src={URL.createObjectURL(image)} 
                alt={`Preview ${index}`} 
                class="h-24 w-24 object-cover rounded"
              />
              <button 
                onClick$={() => handleRemoveImage(index)}
                class="absolute -top-2 -right-2 bg-button-color-1 text-white rounded-full w-6 h-6 flex items-center justify-center"
              >
                ×
              </button>
            </div>
          ))}
        </div>

      </div>
      <div class="relative">
        <textarea
          ref={textareaRef}
          bind:value={content}
          placeholder="본문을 입력해주세요"
          class="w-full min-h-[50vh] p-4 bg-white border border-text-default rounded-lg focus:outline-none resize-none leading-relaxed whitespace-pre-wrap"
          style={{
            backgroundImage: 'linear-gradient(#f1f1f1 1px, transparent 1px)',
                backgroundSize: '100% 1.5rem',
                lineHeight: '1.5rem',
                backgroundAttachment: 'local',
                backgroundPositionY: '0.75rem',
          }}
        />
      </div>
      {showPhotoUploadModal.value &&  
      <div class="fixed inset-0 bg-black bg-opacity-45 flex items-center justify-center z-50" onClick$={() => showPhotoUploadModal.value = false}>
      <div class="bg-white rounded-lg w-[400px] p-6 shadow-xl relative" onClick$={(e) => e.stopPropagation()}>
        <button 
          class="absolute top-4 right-4 text-xl text-black" 
          onClick$={() => showPhotoUploadModal.value = false}
          aria-label="닫기"
        >
          <i class="bi bi-x-lg"></i>
        </button>

        <h2 class="text-3xl font-bold text-center text-black">사진 업로드</h2>
        <p class="text-xs p-2 text-gray-500 text-center border-b-2 border-black mb-6">
          소중한 순간들을 기록하고 공유하세요
        </p>

        <div 
          class={`border-2 border-dashed rounded-md h-32 flex flex-col items-center justify-center text-sm cursor-pointer transition-colors ${
            fileInfo.value 
              ? 'border-green-300 bg-green-50 text-green-700' 
              : 'border-gray-300 bg-gray-100 text-gray-500 hover:border-blue-400'
          }`}
          onDragOver$={(e) => e.preventDefault()}   
          onDrop$={async (e) => {
            e.preventDefault();
            const files = e.dataTransfer?.files;
            if (files && files.length > 0) {
              await handleFileSelect(files[0]);
            }
          }}
          onClick$={async () => {
            if (fileRef.value) {
              try {
          
                console.log('업로드됨:', { 
                  file: fileRef.value,
                  fileInfo: fileInfo.value
                });
          
                // 업로드 후 초기화
                fileInfo.value = null;
                fileRef.value = null;
                showPhotoUploadModal.value = false;
              } catch (err) {
                console.error('업로드 실패:', err);
                error.value = '파일 업로드 중 오류가 발생했습니다.';
              }
            }
          }}
        >
          {fileInfo.value ? (
            <div class="text-center p-4">
              <i class="bi bi-check-circle-fill text-2xl mb-1"></i>
              <p class="font-medium">{fileInfo.value.name}</p>
              <p class="text-xs">{(fileInfo.value.size / 1024).toFixed(1)} KB</p>
            </div>
          ) : (
            <div class="text-center p-4">
              <i class="bi bi-image-fill text-2xl mb-1"></i>
              <p>클릭 또는 사진을 드래그하세요</p>
              <p class="text-xs mt-1">JPG, PNG, GIF</p>
            </div>
          )}
        </div>

        {error.value && (
          <p class="text-red-500 text-sm mt-2">{error.value}</p>
        )}

        <button 
          class="mt-6 w-full bg-[#FFAD84] hover:bg-[#ff9e6b] text-[#4b3c28] font-semibold py-2 rounded-md flex justify-center items-center gap-1 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={!fileInfo.value}
          onClick$={async () => {
            if (fileRef.value) {
              try {
                console.log('Uploading:', { 
                  file: fileRef.value,
                  fileInfo: fileInfo.value
                });
                
                selectedImages.value = [...selectedImages.value, fileRef.value];
                fileInfo.value = null;
                fileRef.value = null;
              } catch (err) {
                console.error('업로드 실패:', err);
                error.value = '파일 업로드 중 오류가 발생했습니다.';
              }
            }
          }}
        >
          업로드 <i class="bi bi-cloud-upload"></i>
        </button>
      </div>
    </div>
    }
    </div>
  );
});
