"use client";

import { useEffect, useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { useTranslation } from "@/lib/i18n";
import {
  getGoals,
  getGoal,
  createGoal,
  updateGoal,
  deleteGoal,
  generateGoalPlan,
  getGoalReport,
  getGroups,
  Goal,
  GoalPlanResult,
  GoalReport,
  Group,
} from "@/lib/api";
import PageActionBar from "@/components/features/PageActionBar";
import GoalActionButtons from "@/components/features/GoalActionButtons";
import IconButton from "@/components/features/IconButton";

export default function GoalsPage() {
  const { token } = useAuth();
  const { t, locale } = useTranslation();
  const router = useRouter();
  const [goals, setGoals] = useState<Goal[]>([]);
  const [groups, setGroups] = useState<Group[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [selectedGoal, setSelectedGoal] = useState<(Goal & { tasks?: unknown[] }) | null>(null);
  const [planResult, setPlanResult] = useState<GoalPlanResult | null>(null);
  const [report, setReport] = useState<GoalReport | null>(null);
  const [aiLoading, setAiLoading] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const [formTitle, setFormTitle] = useState("");
  const [formDate, setFormDate] = useState("");
  const [formGroup, setFormGroup] = useState("");

  const dateLocale = locale === "ua" ? "uk-UA" : locale === "cs" ? "cs-CZ" : locale === "he" ? "he-IL" : "ru-RU";

  const loadData = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    try {
      const [goalsRes, groupsRes] = await Promise.all([
        getGoals(token),
        getGroups(token),
      ]);
      setGoals(goalsRes.data || []);
      setGroups(groupsRes.data || []);
    } catch (err) {
      console.error("Load error:", err);
      setError(t("common.error"));
    } finally {
      setLoading(false);
    }
  }, [token, t]);

  useEffect(() => {
    if (!token) {
      router.replace("/login");
      return;
    }
    loadData();
  }, [token, router, loadData]);

  async function handleCreate(e: React.FormEvent) {
    e.preventDefault();
    if (!token || !formTitle.trim()) return;
    try {
      await createGoal(token, {
        title: formTitle.trim(),
        target_date: formDate || null,
        group_id: formGroup || null,
      });
      setFormTitle("");
      setFormDate("");
      setFormGroup("");
      setShowForm(false);
      loadData();
    } catch (err) {
      console.error("Create error:", err);
      setError(t("common.error"));
    }
  }

  async function handleSelectGoal(goal: Goal) {
    if (!token) return;
    try {
      const res = await getGoal(token, goal.id);
      setSelectedGoal(res.data);
      setPlanResult(null);
      setReport(null);
    } catch (err) {
      console.error("Load goal error:", err);
    }
  }

  async function handleGeneratePlan(goalId: string) {
    if (!token) return;
    setAiLoading("plan");
    setError(null);
    try {
      const res = await generateGoalPlan(token, goalId);
      setPlanResult(res.data);
      const updated = await getGoal(token, goalId);
      setSelectedGoal(updated.data);
      loadData();
    } catch (err) {
      console.error("Plan error:", err);
      setError(t("common.error"));
    } finally {
      setAiLoading(null);
    }
  }

  async function handleGetReport(goalId: string) {
    if (!token) return;
    setAiLoading("report");
    setError(null);
    try {
      const res = await getGoalReport(token, goalId);
      setReport(res.data);
    } catch (err) {
      console.error("Report error:", err);
      setError(t("common.error"));
    } finally {
      setAiLoading(null);
    }
  }

  async function handleUpdateProgress(goalId: string, pct: number) {
    if (!token) return;
    try {
      await updateGoal(token, goalId, { progress_pct: pct } as Partial<Goal>);
      loadData();
      if (selectedGoal && selectedGoal.id === goalId) {
        setSelectedGoal({ ...selectedGoal, progress_pct: pct });
      }
    } catch (err) {
      console.error("Update error:", err);
    }
  }

  async function handleDelete(goalId: string) {
    if (!token) return;
    if (!confirm(t("tasks.confirmDelete"))) return;
    try {
      await deleteGoal(token, goalId);
      setSelectedGoal(null);
      loadData();
    } catch (err) {
      console.error("Delete error:", err);
    }
  }

  function formatDate(d: string | null) {
    if (!d) return t("tasks.noDue");
    return new Date(d).toLocaleDateString(dateLocale, { day: "numeric", month: "short", year: "numeric" });
  }

  function progressColor(pct: number) {
    if (pct >= 80) return "bg-green-500";
    if (pct >= 50) return "bg-blue-500";
    if (pct >= 20) return "bg-yellow-500";
    return "bg-gray-400";
  }

  if (!token) return null;

  return (
    <div className="space-y-4 pb-24 sm:pb-8 px-4 sm:px-0">
      <PageActionBar
        title={t("goals.title")}
        showAdd
        onToggleAdd={() => setShowForm(!showForm)}
        addOpen={showForm}
        t={t}
      />

      {error && (
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 text-red-700 dark:text-red-300 text-sm">
          {error}
          <button onClick={() => setError(null)} className="ml-2 underline">{t("tasks.close")}</button>
        </div>
      )}

      {showForm && (
        <form onSubmit={handleCreate} className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4 space-y-3">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t("tasks.form.title")}</label>
            <input
              type="text"
              value={formTitle}
              onChange={(e) => setFormTitle(e.target.value)}
              className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[44px]"
              required
            />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t("tasks.form.dueDate")}</label>
              <input
                type="date"
                value={formDate}
                onChange={(e) => setFormDate(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500 min-h-[44px]"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{t("tasks.form.group")}</label>
              <select
                value={formGroup}
                onChange={(e) => setFormGroup(e.target.value)}
                className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500 min-h-[44px]"
              >
                <option value="">{t("tasks.form.noGroup")}</option>
                {groups.map((g) => (
                  <option key={g.id} value={g.id}>{g.icon ? g.icon + " " : ""}{g.name}</option>
                ))}
              </select>
            </div>
          </div>
          <button
            type="submit"
            className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors min-h-[44px]"
          >
            {t("goals.add")}
          </button>
        </form>
      )}

      {loading ? (
        <div className="flex justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
        </div>
      ) : goals.length === 0 ? (
        <div className="text-center py-16">
          <div className="text-5xl mb-4 opacity-50">&#127919;</div>
          <p className="text-gray-500 dark:text-gray-400 text-lg font-medium">{t("goals.title")}</p>
        </div>
      ) : (
        <div className="space-y-2">
          {goals.map((goal) => (
            <button
              key={goal.id}
              onClick={() => handleSelectGoal(goal)}
              className={`w-full text-left bg-white dark:bg-gray-900 rounded-xl border p-4 transition-all hover:shadow-md ${
                selectedGoal?.id === goal.id
                  ? "border-blue-500 ring-2 ring-blue-200 dark:ring-blue-800"
                  : "border-gray-200 dark:border-gray-800"
              }`}
            >
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    {goal.group_icon && <span className="text-lg">{goal.group_icon}</span>}
                    <h3 className="font-semibold text-gray-900 dark:text-white truncate">{goal.title}</h3>
                  </div>
                  <div className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
                    <span>{formatDate(goal.target_date)}</span>
                    {goal.group_name && (
                      <span className="px-2 py-0.5 rounded-full text-xs" style={{ backgroundColor: (goal.group_color || "#6b7280") + "20", color: goal.group_color || "#6b7280" }}>
                        {goal.group_name}
                      </span>
                    )}
                  </div>
                </div>
                <span className="text-sm font-bold text-gray-700 dark:text-gray-300 whitespace-nowrap">
                  {goal.progress_pct}%
                </span>
              </div>
              <div className="mt-3 h-2 bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden">
                <div
                  className={`h-full rounded-full transition-all duration-500 ${progressColor(goal.progress_pct)}`}
                  style={{ width: `${goal.progress_pct}%` }}
                />
              </div>
            </button>
          ))}
        </div>
      )}

      {/* Goal detail panel */}
      {selectedGoal && (
        <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4 space-y-4">
          <div className="flex items-start justify-between">
            <div className="flex-1 min-w-0">
              <h2 className="text-lg font-bold dark:text-white">{selectedGoal.title}</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {formatDate(selectedGoal.target_date)} | {t("goals.progress")}: {selectedGoal.progress_pct}%
              </p>
            </div>
            <IconButton
              icon={
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              }
              label={t("tasks.close")}
              onClick={() => setSelectedGoal(null)}
              variant="default"
              size="md"
            />
          </div>

          {/* Progress slider */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              {t("goals.progress")}: {selectedGoal.progress_pct}%
            </label>
            <input
              type="range"
              min="0"
              max="100"
              value={selectedGoal.progress_pct}
              onChange={(e) => handleUpdateProgress(selectedGoal.id, parseInt(e.target.value))}
              className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600"
            />
          </div>

          {/* AI Action buttons - icon only */}
          <GoalActionButtons
            onPlan={() => handleGeneratePlan(selectedGoal.id)}
            onReport={() => handleGetReport(selectedGoal.id)}
            onDelete={() => handleDelete(selectedGoal.id)}
            planLoading={aiLoading === "plan"}
            reportLoading={aiLoading === "report"}
            t={t}
          />

          {/* Plan result */}
          {planResult && (
            <div className="bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg p-3">
              <h3 className="font-semibold text-purple-800 dark:text-purple-300 mb-2">
                {t("goals.plan")} ({planResult.tasks_created})
              </h3>
              {planResult.plan.weeks ? (
                <div className="space-y-2">
                  {(planResult.plan.weeks as Array<{ week_number: number; focus: string; tasks: Array<{ title: string; duration_hours?: number; day_of_week?: string }> }>).map((week, i) => (
                    <div key={i} className="bg-white dark:bg-gray-800 rounded-lg p-2">
                      <p className="text-sm font-medium text-purple-700 dark:text-purple-300">
                        #{week.week_number}: {week.focus}
                      </p>
                      <ul className="mt-1 space-y-0.5">
                        {(week.tasks || []).map((wt, j) => (
                          <li key={j} className="text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1">
                            <span className="w-1 h-1 bg-purple-400 rounded-full flex-shrink-0" />
                            {wt.title}
                            {wt.duration_hours && <span className="text-gray-400 ml-1">({wt.duration_hours}h)</span>}
                            {wt.day_of_week && <span className="text-gray-400 ml-1">[{wt.day_of_week}]</span>}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              ) : (
                <pre className="text-xs text-gray-600 dark:text-gray-400 whitespace-pre-wrap overflow-auto max-h-64">
                  {JSON.stringify(planResult.plan, null, 2)}
                </pre>
              )}
            </div>
          )}

          {/* AI Report */}
          {report && (
            <div className="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
              <div className="flex items-center justify-between mb-2">
                <h3 className="font-semibold text-green-800 dark:text-green-300">{t("goals.report")}</h3>
                <span className="text-sm text-green-600 dark:text-green-400">
                  {report.stats.done}/{report.stats.total} ({report.stats.pct}%)
                </span>
              </div>
              <p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap">{report.report}</p>
            </div>
          )}

          {/* Existing plan */}
          {selectedGoal.plan && Object.keys(selectedGoal.plan).length > 0 && !planResult && (
            <div className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3">
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-2">{t("goals.plan")}</h3>
              {(selectedGoal.plan as Record<string, unknown>).weeks ? (
                <div className="space-y-2">
                  {((selectedGoal.plan as Record<string, unknown>).weeks as Array<{ week_number: number; focus: string; tasks: Array<{ title: string; duration_hours?: number; day_of_week?: string }> }>).map((week, i) => (
                    <div key={i} className="bg-white dark:bg-gray-900 rounded-lg p-2">
                      <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                        #{week.week_number}: {week.focus}
                      </p>
                      <ul className="mt-1 space-y-0.5">
                        {(week.tasks || []).map((wt, j) => (
                          <li key={j} className="text-xs text-gray-600 dark:text-gray-400 flex items-center gap-1">
                            <span className="w-1 h-1 bg-gray-400 rounded-full flex-shrink-0" />
                            {wt.title}
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
                </div>
              ) : (
                <pre className="text-xs text-gray-600 dark:text-gray-400 whitespace-pre-wrap overflow-auto max-h-40">
                  {JSON.stringify(selectedGoal.plan, null, 2)}
                </pre>
              )}
            </div>
          )}

          {/* Related tasks */}
          {selectedGoal.tasks && selectedGoal.tasks.length > 0 && (
            <div>
              <h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-2">
                {t("nav.tasks")} ({selectedGoal.tasks.length})
              </h3>
              <div className="space-y-1 max-h-48 overflow-y-auto">
                {(selectedGoal.tasks as Array<{ id: string; title: string; status: string }>).map((task) => (
                  <div
                    key={task.id}
                    className="flex items-center gap-2 p-2 bg-gray-50 dark:bg-gray-800 rounded-lg"
                  >
                    <span className={`w-2 h-2 rounded-full flex-shrink-0 ${
                      task.status === "done" || task.status === "completed" ? "bg-green-500" :
                      task.status === "in_progress" ? "bg-blue-500" :
                      "bg-gray-400"
                    }`} />
                    <span className="text-sm text-gray-700 dark:text-gray-300 truncate">{task.title}</span>
                    <span className="text-xs text-gray-400 ml-auto flex-shrink-0">{t(`tasks.status.${task.status}`)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
