"use client"

import { useCallback, useEffect, useState } from "react"
import { ChevronLeft, ChevronRight, Loader2, RotateCw } from "lucide-react"

import SafeImage from "@/components/common/safe-img"
import { WEEKDAYS } from "@/components/practice/week-strip.component"
import { ApiEndpoint } from "@/lib/services/api.service"
import { useApi } from "@/lib/services/axios.service"
import { PracticeLogDto, StreakMonthDto } from "@/lib/dto/practice.dto"
import { faNumber } from "@/lib/helpers/format.helper"
import { cn } from "@/lib/utils"
import { jalaliDay } from "@/lib/helpers/date.helper"

const dayTitle = (date: string) => jalaliDay(date)

export default function StreakCalendar({ best, refreshKey }: { best: number; refreshKey?: unknown }) {
  const [month, setMonth] = useState<string | null>(null)
  const [data, setData] = useState<StreakMonthDto | null>(null)
  const [selected, setSelected] = useState<string | null>(null)
  const [dayLogs, setDayLogs] = useState<PracticeLogDto[]>([])
  const [monthFailed, setMonthFailed] = useState(false)
  const [dayFailed, setDayFailed] = useState(false)

  const [{ loading }, fetchMonth] = useApi<StreakMonthDto>({ url: ApiEndpoint("practice", "month"), method: "GET" })
  const [{ loading: dayLoading }, fetchDay] = useApi<PracticeLogDto[]>({ url: ApiEndpoint("practice", "list"), method: "GET" })

  const load = useCallback((m: string | null) => {
    fetchMonth({ params: m ? { month: m } : {} }).then(
      (response) => {
        const result = response?.body?.data
        if (result) setData(result)
        setMonthFailed(!result)
      },
      () => setMonthFailed(true),
    )
  }, [fetchMonth])

  useEffect(() => {
    load(month)
  }, [load, month, refreshKey])

  function go(next: string | null) {
    if (!next) return
    setSelected(null)
    setDayLogs([])
    setMonth(next)
  }

  function pick(date: string, count: number) {
    if (count === 0) {
      setSelected(null)
      return
    }
    setSelected(date)
    setDayLogs([])
    setDayFailed(false)
    fetchDay({ params: { date } }).then(
      (response) => setDayLogs(response?.body?.data ?? []),
      () => setDayFailed(true),
    )
  }

  return (
    <section className="bg-canvas border border-line rounded-card p-4">
      <div className="flex items-center justify-between">
        <h2 className="font-bold text-body">تقویم استمرار</h2>
        <span className="text-micro text-ink-soft">رکورد: {faNumber(best)} روز</span>
      </div>

      <div className="flex items-center justify-between mt-3">
        <button
          type="button"
          onClick={() => go(data?.previous ?? null)}
          disabled={!data?.previous}
          aria-label="ماه قبل"
          className="w-9 h-9 rounded-xl grid place-items-center hover:bg-paper-2 disabled:opacity-30"
        >
          <ChevronRight className="w-5 h-5" />
        </button>
        <div className="text-center">
          <p className="text-body font-extrabold flex items-center gap-1.5 justify-center">
            {data?.title ?? "…"}
            {loading && <Loader2 className="w-3.5 h-3.5 animate-spin text-ink-soft" aria-hidden="true" />}
          </p>
          {data && <p className="text-micro text-ink-soft">{faNumber(data.practised_days)} روز تمرین</p>}
        </div>
        <button
          type="button"
          onClick={() => go(data?.next ?? null)}
          disabled={!data?.next}
          aria-label="ماه بعد"
          className="w-9 h-9 rounded-xl grid place-items-center hover:bg-paper-2 disabled:opacity-30"
        >
          <ChevronLeft className="w-5 h-5" />
        </button>
      </div>

      {monthFailed && !loading && (
        <RetryLine text="این ماه بارگذاری نشد." onRetry={() => load(month)} />
      )}

      <div className="grid grid-cols-7 gap-1.5 mt-3">
        {WEEKDAYS.map((w) => (
          <span key={w} className="text-micro text-center text-ink-soft">{w}</span>
        ))}
        {data && Array.from({ length: data.first_weekday }, (_, i) => <span key={`pad-${i}`} />)}
        {data?.days.map((day) => (
          <button
            key={day.date}
            type="button"
            onClick={() => pick(day.date, day.count)}
            aria-label={`${dayTitle(day.date)}${day.count ? `، ${faNumber(day.count)} تمرین` : ""}`}
            aria-pressed={selected === day.date}
            className={cn(
              "relative aspect-square rounded-lg grid place-items-center text-micro font-bold tabular-nums transition",
              day.status === "done" && "bg-sienna text-canvas",
              day.status === "frozen" && "bg-ultra-soft text-ultra",
              day.status === "today" && "border-2 border-dashed border-sienna text-sienna",
              day.status === "missed" && "bg-paper-2 text-ink-soft",
              (day.status === "future" || day.status === "none") && "border border-line text-ink-soft/50",
              selected === day.date && "ring-2 ring-ochre ring-offset-1 ring-offset-canvas"
            )}
          >
            {faNumber(day.day)}
            {day.count > 1 && <span className="absolute bottom-0.5 w-1 h-1 rounded-full bg-canvas" aria-hidden="true" />}
          </button>
        ))}
      </div>

      <div className="flex gap-4 text-micro text-ink-soft mt-3">
        <span className="flex items-center gap-1"><i className="w-3 h-3 rounded bg-sienna" /> تمرین</span>
        <span className="flex items-center gap-1"><i className="w-3 h-3 rounded bg-ultra-soft" /> یخ‌زدگی</span>
        <span className="flex items-center gap-1"><i className="w-3 h-3 rounded bg-paper-2" /> بدون تمرین</span>
      </div>

      {selected && (
        <div className="mt-4 pt-3 border-t border-line">
          <p className="text-caption font-bold mb-2">{dayTitle(selected)}</p>
          {dayLoading ? (
            <Loader2 className="w-4 h-4 animate-spin text-ink-soft" />
          ) : dayFailed ? (
            <RetryLine text="تمرین‌های این روز بارگذاری نشد." onRetry={() => pick(selected, 1)} />
          ) : dayLogs.length === 0 ? (
            <p className="text-caption text-ink-soft">این روز تکلیف فرستاده بودی.</p>
          ) : (
            <div className="flex overflow-x-auto no-scrollbar [&>*:not(:last-child)]:ml-2">
              {dayLogs.map((log) => (
                <figure key={log.id} className="w-24 shrink-0">
                  <span className="relative block aspect-square rounded-xl overflow-hidden bg-paper-2">
                    <SafeImage src={log.photo} />
                  </span>
                  <figcaption className="text-micro mt-1 truncate">{log.title}</figcaption>
                  <span className="text-micro text-ink-soft">{faNumber(log.minutes)} دقیقه</span>
                </figure>
              ))}
            </div>
          )}
        </div>
      )}
    </section>
  )
}

/** A failed part of the calendar: one line with a retry. */
function RetryLine({ text, onRetry }: { text: string; onRetry: () => void }) {
  return (
    <p role="alert" className="mt-3 flex items-center justify-between gap-2 text-caption text-ink-soft bg-paper-2 rounded-xl px-3 py-2">
      {text}
      <button type="button" onClick={onRetry} className="flex items-center gap-1 font-bold text-sienna shrink-0">
        <RotateCw className="w-3.5 h-3.5" aria-hidden="true" />
        تلاش دوباره
      </button>
    </p>
  )
}
