"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardContent, Input, Modal, PageHeader, Select, Textarea } from "@/components/ui/index";
import { useLanguage } from "@/i18n/LanguageContext";
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

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

function toYMD(date: Date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

function isSameDay(a: Date, b: Date) {
  return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function formatCalendarMonth(date: Date, isArabic: boolean) {
  return new Intl.DateTimeFormat(isArabic ? "ar-SA-u-ca-gregory" : "en-US", {
    month: "long",
    year: "numeric",
  }).format(date);
}

function formatCalendarDate(date: Date, isArabic: boolean) {
  return new Intl.DateTimeFormat(isArabic ? "ar-SA-u-ca-gregory" : "en-US", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).format(date);
}

function priorityChipClass(priority?: string) {
  switch ((priority ?? "").toUpperCase()) {
    case "LOW":
      return "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300";
    case "MEDIUM":
      return "bg-sky-500/15 text-sky-700 dark:text-sky-300";
    case "HIGH":
      return "bg-amber-500/15 text-amber-700 dark:text-amber-300";
    case "URGENT":
      return "bg-rose-500/15 text-rose-700 dark:text-rose-300";
    default:
      return "bg-primary/10 text-primary";
  }
}

export default function UtilitiesCalendarPage() {
  const router = useRouter();
  const { language } = useLanguage();
  const isArabic = language === "ar";
  const weekDays = isArabic ? WEEK_DAYS_AR : WEEK_DAYS_EN;

  const [currentMonth, setCurrentMonth] = useState(() => new Date(new Date().getFullYear(), new Date().getMonth(), 1));
  const [tasks, setTasks] = useState<any[]>([]);
  const [statusFilter, setStatusFilter] = useState("");
  const [loading, setLoading] = useState(true);
  const [openAdd, setOpenAdd] = useState(false);
  const [selectedDate, setSelectedDate] = useState<Date>(new Date());
  const [newTitle, setNewTitle] = useState("");
  const [newDesc, setNewDesc] = useState("");
  const [newPriority, setNewPriority] = useState("MEDIUM");
  const [newAssigneeId, setNewAssigneeId] = useState("");
  const [assignableUsers, setAssignableUsers] = useState<Array<{ id: string; name: string }>>([]);
  const [creating, setCreating] = useState(false);
  const [openView, setOpenView] = useState(false);
  const [selectedTask, setSelectedTask] = useState<any | null>(null);

  const fetchTasks = useMemo(
    () => async () => {
      setLoading(true);
      try {
        const params = new URLSearchParams({
          pageSize: "300",
          ...(statusFilter && { status: statusFilter }),
        });
        const res = await fetch(`/api/tasks?${params}`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error ?? "Failed");
        setTasks(json.data?.items ?? []);
      } catch (e: any) {
        setTasks([]);
        toast.error(e.message ?? (isArabic ? "تعذر تحميل المهام" : "Failed to load tasks"));
      } finally {
        setLoading(false);
      }
    },
    [isArabic, statusFilter]
  );

  useEffect(() => {
    fetchTasks();
  }, [fetchTasks]);

  useEffect(() => {
    const loadAssignableUsers = async () => {
      try {
        const res = await fetch("/api/users/assignable?pageSize=100");
        const json = await res.json();
        if (!res.ok) return;
        setAssignableUsers((json.data?.items ?? []).map((u: any) => ({ id: u.id, name: u.name })));
      } catch {
        setAssignableUsers([]);
      }
    };
    loadAssignableUsers();
  }, []);

  const monthCells = useMemo(() => {
    const start = new Date(currentMonth.getFullYear(), currentMonth.getMonth(), 1);
    const end = new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 0);
    const lead = start.getDay();
    const total = end.getDate();
    const cells: Array<Date | null> = [];
    for (let i = 0; i < lead; i += 1) cells.push(null);
    for (let d = 1; d <= total; d += 1) cells.push(new Date(currentMonth.getFullYear(), currentMonth.getMonth(), d));
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  }, [currentMonth]);

  const tasksByDay = useMemo(() => {
    const map: Record<string, any[]> = {};
    for (const t of tasks) {
      if (!t.dueDate) continue;
      const key = toYMD(new Date(t.dueDate));
      if (!map[key]) map[key] = [];
      map[key].push(t);
    }
    return map;
  }, [tasks]);

  const monthTitle = useMemo(
    () => formatCalendarMonth(currentMonth, isArabic),
    [currentMonth, isArabic]
  );

  const openAddFor = (date: Date) => {
    setSelectedDate(date);
    setNewTitle("");
    setNewDesc("");
    setNewPriority("MEDIUM");
    setNewAssigneeId("");
    setOpenAdd(true);
  };

  const createTask = async () => {
    if (!newTitle.trim()) {
      toast.error(isArabic ? "عنوان المهمة مطلوب" : "Task title is required");
      return;
    }
    setCreating(true);
    try {
      const res = await fetch("/api/tasks", {
        method: "POST",
        credentials: "include",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: newTitle.trim(),
          description: newDesc.trim() || null,
          dueDate: toYMD(selectedDate),
          priority: newPriority,
          status: "TODO",
          assignedToId: newAssigneeId || null,
        }),
      });
      const json = await res.json();
      if (res.status === 401) {
        throw new Error(isArabic ? "انتهت الجلسة، أعد تسجيل الدخول" : "Session expired, please sign in again");
      }
      if (!res.ok) throw new Error(json.error ?? "Failed");
      toast.success(isArabic ? "تم إنشاء المهمة" : "Task created");
      setOpenAdd(false);
      fetchTasks();
    } catch (e: any) {
      toast.error(e.message ?? (isArabic ? "تعذر إنشاء المهمة" : "Failed to create task"));
    } finally {
      setCreating(false);
    }
  };

  const openTaskView = (task: any) => {
    setSelectedTask(task);
    setOpenView(true);
  };

  return (
    <AppShell breadcrumbs={[{ label: isArabic ? "التقويم" : "Calendar" }]}>
      <PageHeader
        title={isArabic ? "التقويم" : "Calendar"}
        description={isArabic ? "تقويم شهري للمهام مع إضافة سريعة." : "Monthly task calendar with quick add."}
      />

      <Card className="mb-4">
        <CardContent className="grid grid-cols-1 md:grid-cols-4 gap-3 items-end">
          <Select
            label={isArabic ? "حالة المهام" : "Task Status"}
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            options={[
              { value: "", label: isArabic ? "الكل" : "All" },
              { value: "TODO", label: isArabic ? "للتنفيذ" : "To Do" },
              { value: "IN_PROGRESS", label: isArabic ? "قيد التنفيذ" : "In Progress" },
              { value: "DONE", label: isArabic ? "منجز" : "Done" },
              { value: "CANCELLED", label: isArabic ? "ملغى" : "Cancelled" },
            ]}
          />
          <div className="flex items-center gap-2">
            <Button type="button" variant="outline" onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1))}>
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <Button type="button" variant="outline" onClick={() => setCurrentMonth(new Date())}>
              {isArabic ? "اليوم" : "Today"}
            </Button>
            <Button type="button" variant="outline" onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1))}>
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
          <div className="md:col-span-2 text-center text-lg font-semibold">{monthTitle}</div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-3">
          {loading ? (
            <div className="py-10 text-center text-muted-foreground">{isArabic ? "جاري التحميل..." : "Loading..."}</div>
          ) : (
            <>
              <div className="grid grid-cols-7 border border-border rounded-t-lg overflow-hidden">
                {weekDays.map((d) => (
                  <div key={d} className="bg-muted/40 text-center text-xs font-semibold py-2 border-e border-border last:border-e-0">
                    {d}
                  </div>
                ))}
              </div>
              <div className="grid grid-cols-7 border-x border-b border-border rounded-b-lg overflow-hidden">
                {monthCells.map((cell, idx) => {
                  if (!cell) return <div key={`empty-${idx}`} className="min-h-[130px] bg-muted/10 border border-border/50" />;
                  const key = toYMD(cell);
                  const dayTasks = tasksByDay[key] ?? [];
                  const today = isSameDay(cell, new Date());
                  return (
                    <div
                      key={key}
                      className="min-h-[130px] p-1.5 border border-border/50 bg-card cursor-pointer hover:bg-accent/20 transition-colors"
                      onClick={() => openAddFor(cell)}
                    >
                      <div className="flex items-center justify-between mb-1">
                        <span className={cn("text-xs font-semibold px-1.5 py-0.5 rounded", today && "bg-primary/10 text-primary")}>{cell.getDate()}</span>
                      </div>
                      <div className="space-y-1">
                        {dayTasks.slice(0, 3).map((t) => (
                          <div
                            key={t.id}
                            className={cn("text-[11px] rounded px-1.5 py-1 truncate cursor-pointer hover:opacity-85", priorityChipClass(t.priority))}
                            title={t.title}
                            onClick={(e) => {
                              e.stopPropagation();
                              openTaskView(t);
                            }}
                          >
                            {t.title}
                          </div>
                        ))}
                        {dayTasks.length > 3 && <div className="text-[11px] text-muted-foreground px-1.5">+{dayTasks.length - 3}</div>}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}
        </CardContent>
      </Card>

      <Modal
        open={openAdd}
        onClose={() => setOpenAdd(false)}
        title={isArabic ? "إضافة مهمة" : "Add Task"}
        description={isArabic ? `التاريخ: ${formatCalendarDate(selectedDate, true)}` : `Date: ${formatCalendarDate(selectedDate, false)}`}
      >
        <div className="p-6 space-y-4">
          <Input label={isArabic ? "عنوان المهمة" : "Task Title"} value={newTitle} onChange={(e) => setNewTitle(e.target.value)} />
          <Input
            label={isArabic ? "التاريخ" : "Date"}
            type="date"
            value={toYMD(selectedDate)}
            disabled
          />
          <Select
            label={isArabic ? "الأولوية" : "Priority"}
            value={newPriority}
            onChange={(e) => setNewPriority(e.target.value)}
            options={[
              { value: "LOW", label: isArabic ? "منخفضة" : "Low" },
              { value: "MEDIUM", label: isArabic ? "متوسطة" : "Medium" },
              { value: "HIGH", label: isArabic ? "مرتفعة" : "High" },
              { value: "URGENT", label: isArabic ? "عاجلة" : "Urgent" },
            ]}
          />
          <Select
            label={isArabic ? "إسناد إلى" : "Assign To"}
            value={newAssigneeId}
            onChange={(e) => setNewAssigneeId(e.target.value)}
            options={[
              { value: "", label: isArabic ? "غير مُسند" : "Unassigned" },
              ...assignableUsers.map((u) => ({ value: u.id, label: u.name })),
            ]}
          />
          <Textarea label={isArabic ? "الوصف" : "Description"} rows={3} value={newDesc} onChange={(e) => setNewDesc(e.target.value)} />
          <div className="flex justify-end gap-2">
            <Button type="button" variant="outline" onClick={() => setOpenAdd(false)} disabled={creating}>
              {isArabic ? "إلغاء" : "Cancel"}
            </Button>
            <Button type="button" onClick={createTask} loading={creating}>
              {isArabic ? "حفظ المهمة" : "Save Task"}
            </Button>
          </div>
        </div>
      </Modal>

      <Modal
        open={openView}
        onClose={() => setOpenView(false)}
        title={isArabic ? "تفاصيل المهمة" : "Task Details"}
      >
        <div className="p-6 space-y-3">
          {selectedTask ? (
            <>
              <div>
                <p className="text-xs text-muted-foreground">{isArabic ? "العنوان" : "Title"}</p>
                <p className="font-medium">{selectedTask.title}</p>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <p className="text-xs text-muted-foreground">{isArabic ? "الأولوية" : "Priority"}</p>
                  <p>{selectedTask.priority ?? "—"}</p>
                </div>
                <div>
                  <p className="text-xs text-muted-foreground">{isArabic ? "الحالة" : "Status"}</p>
                  <p>{selectedTask.status ?? "—"}</p>
                </div>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">{isArabic ? "تاريخ الاستحقاق" : "Due Date"}</p>
                <p>{selectedTask.dueDate ? formatCalendarDate(new Date(selectedTask.dueDate), isArabic) : "—"}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">{isArabic ? "الوصف" : "Description"}</p>
                <p className="text-sm">{selectedTask.description || "—"}</p>
              </div>
              <div className="flex justify-end gap-2 pt-2">
                <Button type="button" variant="outline" onClick={() => setOpenView(false)}>
                  {isArabic ? "إغلاق" : "Close"}
                </Button>
                <Button
                  type="button"
                  onClick={() => {
                    if (!selectedTask?.id) return;
                    setOpenView(false);
                    router.push(`/tasks/${selectedTask.id}`);
                  }}
                >
                  {isArabic ? "فتح المهمة" : "Open Task"}
                </Button>
              </div>
            </>
          ) : null}
        </div>
      </Modal>
    </AppShell>
  );
}
