"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Plus, X, Loader2 } from "lucide-react";

interface SurveyQuestion {
  id: string;
  title: string;
  sortOrder: number;
}

interface Survey {
  id: string;
  title: string;
  isActive: boolean;
  questions: SurveyQuestion[];
}

export default function EditSurvey() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [title, setTitle] = useState("");
  const [questions, setQuestions] = useState<string[]>([""]);
  const [isActive, setIsActive] = useState(true);
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    (async () => {
      const token = localStorage.getItem("auth_token");
      const res = await fetch(`/api/surveys/${id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const survey: Survey = await res.json();
        setTitle(survey.title);
        setIsActive(survey.isActive);
        setQuestions(survey.questions.map((q) => q.title));
      }
      setLoading(false);
    })();
  }, [id]);

  const addQuestion = () => setQuestions([...questions, ""]);
  const removeQuestion = (i: number) => {
    if (questions.length <= 1) return;
    setQuestions(questions.filter((_, idx) => idx !== i));
  };

  const handleSave = async () => {
    setError("");
    const valid = questions.filter((q) => q.trim());
    if (!title.trim()) { setError("عنوان نظرسنجی را وارد کنید"); return; }
    if (valid.length === 0) { setError("حداقل یک سوال وارد کنید"); return; }

    setSaving(true);
    const token = localStorage.getItem("auth_token");
    try {
      const res = await fetch(`/api/surveys/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({
          title: title.trim(),
          isActive,
          questions: valid.map((q) => ({ title: q.trim() })),
        }),
      });
      if (!res.ok) throw new Error("خطا");
      router.push("/dashboard/admin/surveys");
      router.refresh();
    } catch {
      setError("خطا در ذخیره");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <button
        onClick={() => router.push("/dashboard/admin/surveys")}
        className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-4 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        بازگشت
      </button>

      <h1 className="text-2xl font-bold text-gray-900 mb-6">ویرایش نظرسنجی</h1>

      <div className="space-y-6">
        <div className="border rounded-xl p-6 bg-white">
          <label className="block text-sm font-medium text-gray-700 mb-1">عنوان نظرسنجی</label>
          <input
            className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>

        <div className="border rounded-xl p-6 bg-white">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-gray-900">سوالات</h2>
            <span className="text-xs text-gray-400">{questions.filter(q => q.trim()).length} سوال</span>
          </div>

          <div className="space-y-3">
            {questions.map((q, i) => (
              <div key={i} className="flex items-start gap-2">
                <span className="text-sm text-gray-400 mt-3 min-w-[20px]">{i + 1}.</span>
                <input
                  className="flex-1 px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB]"
                  value={q}
                  onChange={(e) => {
                    const next = [...questions];
                    next[i] = e.target.value;
                    setQuestions(next);
                  }}
                />
                {questions.length > 1 && (
                  <button
                    type="button"
                    onClick={() => removeQuestion(i)}
                    className="mt-2.5 p-1 rounded hover:bg-red-50 transition-colors"
                  >
                    <X className="h-4 w-4 text-red-400" />
                  </button>
                )}
              </div>
            ))}
          </div>

          <Button type="button" variant="outline" className="mt-4 w-full" onClick={addQuestion}>
            <Plus className="h-4 w-4 ml-1" />
            افزودن سوال
          </Button>
        </div>

        <div className="border rounded-xl p-6 bg-white flex items-center justify-between">
          <span className="text-sm font-medium text-gray-700">وضعیت نظرسنجی</span>
          <label className="relative inline-flex items-center cursor-pointer">
            <input
              type="checkbox"
              className="sr-only peer"
              checked={isActive}
              onChange={(e) => setIsActive(e.target.checked)}
            />
            <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#2563EB]" />
          </label>
        </div>

        {error && (
          <div className="text-sm text-red-600 bg-red-50 p-3 rounded-lg">{error}</div>
        )}

        <div className="flex gap-3">
          <Button
            className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : "ذخیره تغییرات"}
          </Button>
          <Button variant="outline" className="flex-1" onClick={() => router.push("/dashboard/admin/surveys")}>
            انصراف
          </Button>
        </div>
      </div>
    </div>
  );
}
