"use client";

import { useState, useMemo, useCallback } from "react";
import {
  Calendar,
  ChevronLeft,
  ChevronRight,
  Plus,
  Clock,
  Loader2,
  Send,
  Trash2,
} from "lucide-react";
import type {
  CalendarEvent,
  SocialPlatform,
} from "@/lib/types/social-media.types";
import PlatformIcon from "./PlatformIcon";

interface CalendarViewProps {
  isAr: boolean;
  events: CalendarEvent[];
  loading: boolean;
  onRefresh: (month?: number, year?: number) => Promise<void>;
}

export default function CalendarView({
  isAr,
  events,
  loading,
  onRefresh,
}: CalendarViewProps) {
  const now = new Date();
  const [month, setMonth] = useState(now.getMonth());
  const [year, setYear] = useState(now.getFullYear());
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [showScheduleForm, setShowScheduleForm] = useState(false);
  const [scheduleLoading, setScheduleLoading] = useState(false);

  // Schedule form state
  const [scheduleContent, setScheduleContent] = useState("");
  const [schedulePlatform, setSchedulePlatform] =
    useState<SocialPlatform>("INSTAGRAM");
  const [scheduleTime, setScheduleTime] = useState("09:00");

  const monthNames = isAr
    ? [
        "يناير",
        "فبراير",
        "مارس",
        "أبريل",
        "مايو",
        "يونيو",
        "يوليو",
        "أغسطس",
        "سبتمبر",
        "أكتوبر",
        "نوفمبر",
        "ديسمبر",
      ]
    : [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
      ];

  const dayHeaders = isAr
    ? ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت"]
    : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstDayOfMonth = new Date(year, month, 1).getDay();

  const calendarDays = useMemo(() => {
    const days: (number | null)[] = [];
    for (let i = 0; i < firstDayOfMonth; i++) days.push(null);
    for (let i = 1; i <= daysInMonth; i++) days.push(i);
    return days;
  }, [firstDayOfMonth, daysInMonth]);

  const eventsByDate = useMemo(() => {
    const map: Record<string, CalendarEvent[]> = {};
    for (const evt of events) {
      if (!evt.scheduledAt) continue;
      const d = new Date(evt.scheduledAt);
      const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
      if (!map[key]) map[key] = [];
      map[key].push(evt);
    }
    return map;
  }, [events]);

  const navigateMonth = useCallback(
    (dir: number) => {
      let newMonth = month + dir;
      let newYear = year;
      if (newMonth < 0) {
        newMonth = 11;
        newYear--;
      } else if (newMonth > 11) {
        newMonth = 0;
        newYear++;
      }
      setMonth(newMonth);
      setYear(newYear);
      onRefresh(newMonth + 1, newYear);
    },
    [month, year, onRefresh],
  );

  const handleSchedule = useCallback(async () => {
    if (!selectedDate || !scheduleContent.trim()) return;
    setScheduleLoading(true);
    try {
      const [h, m] = scheduleTime.split(":").map(Number);
      const scheduledAt = new Date(year, month, parseInt(selectedDate));
      scheduledAt.setHours(h, m, 0, 0);

      await fetch("/api/social/calendar/schedule", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          socialAccountId: "", // Will be selected in real implementation
          platform: schedulePlatform,
          content: scheduleContent,
          scheduledAt: scheduledAt.toISOString(),
        }),
      });
      setShowScheduleForm(false);
      setScheduleContent("");
      onRefresh(month + 1, year);
    } catch {
      // silent
    } finally {
      setScheduleLoading(false);
    }
  }, [
    selectedDate,
    scheduleContent,
    scheduleTime,
    schedulePlatform,
    year,
    month,
    onRefresh,
  ]);

  const handlePublishNow = useCallback(
    async (itemId: string) => {
      try {
        await fetch(`/api/social/calendar/${itemId}/publish-now`, {
          method: "POST",
        });
        onRefresh(month + 1, year);
      } catch {
        // silent
      }
    },
    [month, year, onRefresh],
  );

  const handleDelete = useCallback(
    async (itemId: string) => {
      try {
        await fetch(`/api/social/calendar/${itemId}`, {
          method: "DELETE",
        });
        onRefresh(month + 1, year);
      } catch {
        // silent
      }
    },
    [month, year, onRefresh],
  );

  const selectedDateKey = selectedDate
    ? `${year}-${month}-${parseInt(selectedDate)}`
    : null;
  const selectedEvents = selectedDateKey
    ? eventsByDate[selectedDateKey] || []
    : [];

  const statusColors: Record<string, string> = {
    DRAFT: "bg-slate-200",
    SCHEDULED: "bg-blue-400",
    PUBLISHING: "bg-amber-400",
    PUBLISHED: "bg-emerald-400",
    FAILED: "bg-red-400",
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="p-2 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-500">
            <Calendar className="h-5 w-5 text-white" />
          </div>
          <h3 className="text-lg font-bold text-slate-900">
            {isAr ? "تقويم المحتوى" : "Content Calendar"}
          </h3>
        </div>
        <button
          onClick={() => {
            setSelectedDate(String(now.getDate()));
            setShowScheduleForm(true);
          }}
          className="flex items-center gap-1.5 px-4 py-2 bg-brand-green text-white rounded-xl text-sm font-medium hover:bg-brand-green/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          {isAr ? "جدولة منشور" : "Schedule Post"}
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Calendar grid */}
        <div className="lg:col-span-2 bg-white rounded-2xl border border-slate-200 p-5">
          {/* Month navigation */}
          <div className="flex items-center justify-between mb-4">
            <button
              type="button"
              aria-label="Previous month"
              onClick={() => navigateMonth(-1)}
              className="p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
            >
              <ChevronLeft
                className={`h-5 w-5 text-slate-600 ${isAr ? "rotate-180" : ""}`}
              />
            </button>
            <h4 className="text-base font-semibold text-slate-900">
              {monthNames[month]} {year}
            </h4>
            <button
              type="button"
              aria-label="Next month"
              onClick={() => navigateMonth(1)}
              className="p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
            >
              <ChevronRight
                className={`h-5 w-5 text-slate-600 ${isAr ? "rotate-180" : ""}`}
              />
            </button>
          </div>

          {loading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-8 w-8 animate-spin text-blue-500" />
            </div>
          ) : (
            <>
              {/* Day headers */}
              <div className="grid grid-cols-7 gap-1 mb-1">
                {dayHeaders.map((d) => (
                  <div
                    key={d}
                    className="text-center text-xs font-medium text-slate-500 py-1"
                  >
                    {d}
                  </div>
                ))}
              </div>

              {/* Days */}
              <div className="grid grid-cols-7 gap-1">
                {calendarDays.map((day, i) => {
                  if (day === null) {
                    return <div key={`empty-${i}`} className="aspect-square" />;
                  }
                  const dateKey = `${year}-${month}-${day}`;
                  const dayEvents = eventsByDate[dateKey] || [];
                  const isToday =
                    day === now.getDate() &&
                    month === now.getMonth() &&
                    year === now.getFullYear();
                  const isSelected = selectedDate === String(day);

                  return (
                    <button
                      key={day}
                      onClick={() => {
                        setSelectedDate(String(day));
                        setShowScheduleForm(false);
                      }}
                      className={`aspect-square rounded-xl p-1 text-sm transition-all relative ${
                        isSelected
                          ? "bg-blue-100 ring-2 ring-blue-400"
                          : isToday
                            ? "bg-blue-50 ring-1 ring-blue-200"
                            : "hover:bg-slate-50"
                      }`}
                    >
                      <span
                        className={`text-xs font-medium ${
                          isToday ? "text-blue-700" : "text-slate-700"
                        }`}
                      >
                        {day}
                      </span>
                      {dayEvents.length > 0 && (
                        <div className="absolute bottom-1 left-1/2 -translate-x-1/2 flex gap-0.5">
                          {dayEvents.slice(0, 3).map((evt) => (
                            <div
                              key={evt.id}
                              className={`w-1.5 h-1.5 rounded-full ${
                                evt.calendarColor
                                  ? ""
                                  : statusColors[evt.status] || "bg-slate-300"
                              }`}
                              style={
                                evt.calendarColor
                                  ? { backgroundColor: evt.calendarColor }
                                  : undefined
                              }
                            />
                          ))}
                          {dayEvents.length > 3 && (
                            <span className="text-[8px] text-slate-400">
                              +{dayEvents.length - 3}
                            </span>
                          )}
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>

        {/* Sidebar: selected date events or schedule form */}
        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          {showScheduleForm && selectedDate ? (
            <div>
              <h4 className="font-semibold text-slate-900 mb-4">
                {isAr ? "جدولة منشور جديد" : "Schedule New Post"}
              </h4>
              <div className="space-y-3">
                <textarea
                  value={scheduleContent}
                  onChange={(e) => setScheduleContent(e.target.value)}
                  rows={4}
                  placeholder={isAr ? "محتوى المنشور..." : "Post content..."}
                  className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl resize-none focus:outline-none focus:ring-2 focus:ring-blue-200"
                  dir={isAr ? "rtl" : "ltr"}
                />
                <div className="grid grid-cols-2 gap-2">
                  <select
                    value={schedulePlatform}
                    onChange={(e) =>
                      setSchedulePlatform(e.target.value as SocialPlatform)
                    }
                    className="px-3 py-2 text-sm border border-slate-200 rounded-xl"
                  >
                    <option value="INSTAGRAM">Instagram</option>
                    <option value="FACEBOOK">Facebook</option>
                  </select>
                  <input
                    type="time"
                    value={scheduleTime}
                    onChange={(e) => setScheduleTime(e.target.value)}
                    className="px-3 py-2 text-sm border border-slate-200 rounded-xl"
                  />
                </div>
                <button
                  onClick={handleSchedule}
                  disabled={!scheduleContent.trim() || scheduleLoading}
                  className="w-full py-2.5 bg-blue-600 text-white rounded-xl text-sm font-medium hover:bg-blue-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                  {scheduleLoading ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Calendar className="h-4 w-4" />
                  )}
                  {isAr ? "جدولة" : "Schedule"}
                </button>
              </div>
            </div>
          ) : selectedDate ? (
            <div>
              <div className="flex items-center justify-between mb-4">
                <h4 className="font-semibold text-slate-900">
                  {monthNames[month]} {selectedDate}
                </h4>
                <button
                  onClick={() => setShowScheduleForm(true)}
                  className="p-1.5 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors"
                >
                  <Plus className="h-4 w-4" />
                </button>
              </div>
              {selectedEvents.length === 0 ? (
                <p className="text-sm text-slate-400 text-center py-8">
                  {isAr ? "لا توجد منشورات مجدولة" : "No scheduled posts"}
                </p>
              ) : (
                <div className="space-y-3">
                  {selectedEvents.map((evt) => (
                    <div
                      key={evt.id}
                      className="p-3 bg-slate-50 rounded-xl border border-slate-100"
                    >
                      <div className="flex items-center justify-between mb-2">
                        <PlatformIcon
                          platform={evt.platform}
                          size="sm"
                          showLabel
                        />
                        <span
                          className={`px-2 py-0.5 rounded-full text-[10px] font-medium text-white ${statusColors[evt.status] || "bg-slate-400"}`}
                        >
                          {evt.status}
                        </span>
                      </div>
                      <p className="text-sm text-slate-700 line-clamp-2">
                        {evt.content}
                      </p>
                      {evt.scheduledAt && (
                        <div className="flex items-center gap-1 mt-2 text-xs text-slate-400">
                          <Clock className="h-3 w-3" />
                          {new Date(evt.scheduledAt).toLocaleTimeString(
                            isAr ? "ar-SA" : "en-US",
                            { hour: "2-digit", minute: "2-digit" },
                          )}
                        </div>
                      )}
                      {evt.campaignTag && (
                        <span className="mt-1 inline-block text-[10px] px-1.5 py-0.5 bg-indigo-50 text-indigo-700 rounded">
                          {evt.campaignTag}
                        </span>
                      )}
                      {/* Actions */}
                      {(evt.status === "DRAFT" ||
                        evt.status === "SCHEDULED") && (
                        <div className="flex gap-2 mt-2 pt-2 border-t border-slate-100">
                          <button
                            onClick={() => handlePublishNow(evt.id)}
                            className="flex items-center gap-1 text-xs text-emerald-600 hover:text-emerald-700"
                          >
                            <Send className="h-3 w-3" />
                            {isAr ? "نشر الآن" : "Publish Now"}
                          </button>
                          <button
                            onClick={() => handleDelete(evt.id)}
                            className="flex items-center gap-1 text-xs text-red-500 hover:text-red-600"
                          >
                            <Trash2 className="h-3 w-3" />
                            {isAr ? "حذف" : "Delete"}
                          </button>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-64 text-slate-400">
              <Calendar className="h-10 w-10 mb-2" />
              <p className="text-sm">
                {isAr
                  ? "اختر يوماً لعرض المنشورات"
                  : "Select a date to view posts"}
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
