import { component$, useSignal, $, useContext, useVisibleTask$ } from "@builder.io/qwik";
import type { DocumentHead } from "@builder.io/qwik-city";
import { useNavigate, useLocation, Link, routeLoader$ } from "@builder.io/qwik-city";
import axios from "axios";
import { AppStateContext } from "~/utils/context";
export const useDiaryLoader = routeLoader$( async ({cookie, params}) => {
    try {
      const userid = await axios.get(`http://localhost:8000/api/user/profile/${params.username}`);
      console.log(userid.data.id + "<- 이건 아이디");
        const res = await axios.get(`http://localhost:8000/api/diary/w/${userid.data.id}?skip=0&limit=6`, {
            headers: {
                Authorization: `Bearer ${cookie.get("access_token")?.value}`,
            },
        });
        console.log(res.data);
        return {user:userid.data, diaries: res.data};
    } catch (error : any) {
        console.error(error);
        return error.response?.data?.detail || 'Diary not found';
    }
});
export default component$(() => {
  const navigate = useNavigate();
  const location = useLocation();
  const entryLoader = useDiaryLoader();
  const entries = useSignal<DiaryEntry[]>([]);
  const filteredEntries = useSignal<DiaryEntry[]>([]);
  useVisibleTask$(() => {
    console.log( entryLoader.value.user);
    entries.value = entryLoader.value.diaries as DiaryEntry[];
    filteredEntries.value = entries.value;
  });
  const userData = useContext(AppStateContext);
  const searchQuery = useSignal('');
  const selectedMonth = useSignal(new Date().getMonth() + 1);
  const showMonth = useSignal(false);
  const handleMonthChange = $(() => {
    showMonth.value = !showMonth.value;
  });
  const handleMonthSelect = $((month : number) => {
    selectedMonth.value = month; 
    console.log(selectedMonth.value);
    filteredEntries.value = [...entries.value.filter((entry) => {
      const entryMonth = new Date(entry.created_at).getMonth() + 1;
      return entryMonth === month;
    })];
    console.log(filteredEntries.value);
    showMonth.value = false;
  }); 
  useVisibleTask$(() => {
    handleMonthSelect(new Date().getMonth() + 1);
  });
  const handleSearch = $(() => {
    if(searchQuery.value === '') {
      filteredEntries.value = [...entries.value];
    }
    else {
      filteredEntries.value = [...entries.value.filter((entry) => entry.title.includes(searchQuery.value))];
    }
    console.log(filteredEntries.value);
  });
  return (
    <div class="w-full h-full mx-auto p-8">
      <div class="flex justify-between items-center md:flex-row flex-col mb-6 relative">
        <div class="relative">
          <button onClick$={() => handleMonthChange()} class="bg-diary-color hover:bg-diary-icon-hover md:w-full text-black px-4 py-2 rounded-3xl font-bold transition-all duration-200 flex items-center gap-2 z-10 relative">
            {selectedMonth.value}월 <i class={`bi ${showMonth.value ? 'bi-caret-up' : 'bi-caret-down'} transition-transform duration-200`}></i>
          </button>
          <div class={`absolute top-12 left-0 w-48 bg-white rounded-lg shadow-lg overflow-hidden transition-all duration-300 transform origin-top ${showMonth.value ? 'opacity-100 scale-y-100' : 'opacity-0 scale-y-95 pointer-events-none'}`}>
            <ul class="max-h-60 overflow-y-auto scrollbar-thin">
              {Array.from({ length: 12 }, (_, i) => i + 1).map((month) => ( 
                <li key={month} onClick$={() => { handleMonthSelect(month); }} class={`px-4 py-2 hover:bg-gray-100 cursor-pointer transition-colors ${ month === selectedMonth.value ? 'bg-diary-color/30 font-bold' : '' }`}>
                  {month}월
                </li> 
              ))}
            </ul>
          </div>
        </div>
        <div class="flex lg:flex-row flex-col gap-2 align-center justify-center">
        {/* <i class="bi bi-sort-down h-4 w-4 text-center"></i> */}
        <div class=" bg-diary-icon-hover rounded-3xl">
        <form class="flex items-center gap-2" preventdefault:submit onSubmit$={handleSearch}>
        <input type="text" id="search" class="px-4 py-2 rounded-3xl bg-diary-color/30  focus:outline-none" bind:value={searchQuery}/>
        <button type="submit" class="text-black px-4 py-2 rounded-3xl font-bold transition-colors flex items-center gap-2">
            <i class="bi bi-search"></i>
        </button>
        </form>
        </div>
        {entryLoader.value.user.username === userData.username && (
        <button onClick$={() => navigate(`/${location.params.username}/diary/write`)} class="bg-diary-color hover:bg-diary-icon-hover text-black px-4 py-2 rounded-3xl font-bold transition-colors flex items-center gap-2">
          글쓰기 <i class="bi bi-pencil-fill"></i>
        </button>
        )}
        </div>
      </div>

      <div class="bg-white border-t-2 border-b-2 border-text-default overflow-hidden">
        <div class="divide-y divide-text-default">
            <div class="px-6 py-2 bg-diary-color transition-colors cursor-pointer">
              <div class="flex items-center justify-between">
                <span class="text-base flex-1 text-center whitespace-nowrap overflow-hidden text-ellipsis text-black font-bold text-default">제목</span>
                <span class="text-sm flex-1 text-end whitespace-nowrap overflow-hidden text-ellipsis text-black font-bold text-default">날짜</span>
              </div>
            </div>
          { filteredEntries.value.map((entry) => (
            <div key={entry.id} class="px-6 py-2 hover:bg-gray-50 transition-colors cursor-pointer">
              <Link href={`/${location.params.username}/diary/${entry.id}`} class="flex items-center justify-between">
                <span class="text-base flex-1 text-center whitespace-nowrap overflow-hidden text-ellipsis font-medium text-default">{entry.title}</span>
                <span class="text-sm flex-1 text-end whitespace-nowrap overflow-hidden text-ellipsis font-medium text-default">{new Date(entry.created_at).toLocaleString()}</span>
              </Link>    
            </div>
          ))}
          {Array.from({length: 15 - filteredEntries.value.length}, (_, index) => (
            <div key={index+filteredEntries.value.length} class="px-6 py-2 hover:bg-gray-50 transition-colors cursor-pointer">
            {/* <Link href={`/${location.params.username}/diary/`} class="flex items-center justify-between"> */}
              <span class="text-base flex-1 text-center whitespace-nowrap overflow-hidden text-ellipsis font-medium text-default"> &nbsp;</span>
              <span class="text-sm flex-1 text-end whitespace-nowrap overflow-hidden text-ellipsis font-medium text-default">&nbsp;</span>
            {/* </Link>     */}
          </div>
          ))}

        </div>
      </div>

    </div>
  );
});

export const head: DocumentHead = {
  title: "나의 일기장",
  meta: [
    {
      name: "description",
      content: "나만의 일기장. 매일의 추억을 기록해보세요.",
    },
  ],
};