<script setup>
import Card from '@/components/cards/Card.vue';
import { p2postApi } from '../api/p2postApi'
import { ref } from 'vue';
import InputComboBox from '@/components/inputs/InputComboBox.vue';
import Label from '@/components/labels/Label.vue';
import InputText from '@/components/inputs/InputText.vue';
import Button from '@/components/buttons/Button.vue';
import { ArrowUpTrayIcon, ChatBubbleBottomCenterTextIcon, RocketLaunchIcon, XMarkIcon } from '@heroicons/vue/24/solid';

const newPostUser = ref(null);
const newPostContent = ref("");
const newPostFiles = ref([]);
const newPostFilesPreview = ref([]);
const newPostNetworks = ref([]);

const onFileSelected = (e) => {
  const newFiles = Array.from(e.target.files);

  newFiles.forEach(file => {
    const exists = newPostFiles.value.some(
      f => f.name === file.name && f.size === file.size
    );
    if (!exists) {
      newPostFiles.value.push(file);
      newPostFilesPreview.value.push({
        file,
        url: URL.createObjectURL(file),
        type: file.type
      });
    }
  });

  e.target.value = null;
};

function removePreview(index) {
  const [removed] = newPostFilesPreview.value.splice(index, 1);
  URL.revokeObjectURL(removed.url);
  newPostFiles.value.splice(index, 1);
}

async function createPost(){
  // TODO Select users
  const user = "A4DZSk+TlR+4w39MbiIAQbti+N0H1QlJEhRH2DI6Iubj"
  const content = newPostContent.value
  var medias = []
  for (var file of newPostFilesPreview.value){
    const response = await p2postApi.uploadFile(file.file)
    console.log(response)
    medias.push({type: "local",
      "file_path": response.path})
  }
  // TODO Select networks
  const networks = ["net"]

  const response = await p2postApi.createPosts(user, content, medias, networks)
}

</script>

<template>
<Card class="bg-black border-yellow-400/20 p-6">
<h2 class="text-xl font-bold text-yellow-400 mb-6 flex items-center">
  <ChatBubbleBottomCenterTextIcon class="mr-2 h-5 w-5" />
  Create New Post
</h2>

<div class="space-y-4">
  <div class="grid md:grid-cols-2 gap-4">
    <div>
      <Label class="text-gray-300 mb-2 block">Select User</Label>
      <InputComboBox/>
    </div>

    
      <div class="bg-black border border-yellow-400/20 rounded-lg p-3">
        <div class="flex items-center space-x-3">
          <!-- <img src={user.photo || "/placeholder.svg"} alt="" class="w-10 h-10 rounded-full" /> -->
          <div>
            <p class="text-white font-semibold">{user.nickname}</p>
            <p class="text-xs text-gray-400 font-mono">{user.publicKey}</p>
          </div>
        </div>
      </div>
  </div>

  <div>
    <Label class="text-gray-300 mb-2 block">Post Content</Label>
    <InputText
      value={postContent}
      placeholder="Share your thoughts with the decentralized world..."
      class="bg-black border-yellow-400/30 text-white min-h-24"
    />
  </div>

  <div class="flex gap-4">
    <Button
      @click=""
      variant="outline"
      class="border-yellow-400 text-yellow-400 hover:bg-yellow-400 hover:text-black bg-transparent"
    >
      <ArrowUpTrayIcon class="mr-2 h-4 w-4" />
      Add Files
    </Button>

    <div class="flex-1 bg-black border border-yellow-400/20 rounded-lg p-3">
        <div class="flex flex-wrap gap-2">
            <div key={file} class="flex items-center space-x-2 bg-gray-800 rounded px-2 py-1">
              <File size={14} class="text-yellow-400" />
              <span class="text-white text-sm">{file}</span>
              <Button
                size="sm"
                variant="ghost"
                class="text-red-400 hover:bg-red-400/20 p-0 h-auto"
              >
                <XMarkIcon class="h-4 w-4" />
              </Button>
            </div>
        </div>
      </div>
  </div>

  <div>
    <Label class="text-gray-300 mb-2 block">Select Networks</Label>
    <!-- <div class="grid grid-cols-2 md:grid-cols-3 gap-2">
        <div key={network.id} class="flex items-center space-x-2">
          <Checkbox
            id={network.id}
            checked={selectedNetworks.includes(network.name)}
            onCheckedChange={(checked) => {
              if (checked) {
                setSelectedNetworks((prev) => [...prev, network.name])
              } else {
                setSelectedNetworks((prev) => prev.filter((n) => n !== network.name))
              }
            class="border-yellow-400 data-[state=checked]:bg-yellow-400 data-[state=checked]:border-yellow-400"
          />
          <Label htmlFor={network.id} class="text-white text-sm">
            {network.name}
          </Label>
        </div>
      ))}
    </div> -->
  </div>

  <Button
    @click=""
    class="bg-yellow-400 text-black hover:bg-yellow-300 font-bold"
  >
    <RocketLaunchIcon class="h-4 w-4 mr-2" />
    Post to Networks
  </Button>
</div>
</Card>

<!-- <div class="bg-gray-800 rounded-xl shadow p-4 mb-6 text-white">
    <textarea
        v-model="newPostContent"
        placeholder="Share something with the network..."
        class="w-full p-2 bg-gray-700 border border-gray-600 rounded mb-2"
        rows="3"
    ></textarea>

    
    <div
        v-for="(preview, index) in newPostFilesPreview"
        :key="preview.url"
        class="bg-gray-700 p-2 rounded relative flex items-center justify-center h-40"
        >
       
        <button
            @click="removePreview(index)"
            class="absolute top-1 right-1 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-700"
            title="Remover"
        >
            &times;
        </button>

        
        <img
            v-if="preview.type.startsWith('image/')"
            :src="preview.url"
            class="object-contain max-h-full max-w-full"
            alt="Preview"
        />

        
        <audio
            v-else-if="preview.type.startsWith('audio/')"
            :src="preview.url"
            controls
            class="w-full"
        ></audio>

        
        <video
            v-else-if="preview.type.startsWith('video/')"
            :src="preview.url"
            controls
            class="object-contain max-h-full max-w-full"
        ></video>

        
        <div v-else class="text-sm text-center px-2 break-all">
            {{ preview.file.name }}
        </div>
    </div>


    <div class="flex items-center justify-between">
        <input type="file" multiple @change="onFileSelected" class="text-sm text-white" />
        <button
        @click="createPost"
        class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700"
        >
        Post
        </button>
    </div>
</div> -->
</template>