"use client";

import { useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
  Button,
  ConfirmDialog,
  Field,
  Input,
  Textarea,
  Select,
  Switch,
  Modal,
  PageHeader,
  Badge,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { toFa } from "@/lib/utils";

interface SurveyTag {
  id: number;
  name: string;
}

interface SurveyOption {
  id?: number;
  label?: string;
  tags?: SurveyTag[];
}

// Form-side option: tags edited as a comma-separated string.
interface OptionDraft {
  label: string;
  tags: string;
}

interface SurveyQuestion {
  id: number;
  question?: string;
  description?: string;
  type?: string;
  order?: number;
  is_active?: boolean;
  options?: SurveyOption[];
}

const TYPE_LABELS: Record<string, string> = {
  single: "تک‌گزینه",
  multiple: "چندگزینه",
};

export default function SurveysPage() {
  const { data, loading, error, reload } =
    useList<SurveyQuestion>("/survey-questions");
  const toast = useToast();

  const [editing, setEditing] = useState<SurveyQuestion | null>(null);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);

  const [question, setQuestion] = useState("");
  const [description, setDescription] = useState("");
  const [type, setType] = useState("single");
  const [order, setOrder] = useState("0");
  const [isActive, setIsActive] = useState(true);
  const [options, setOptions] = useState<OptionDraft[]>([
    { label: "", tags: "" },
  ]);

  const [deleting, setDeleting] = useState<SurveyQuestion | null>(null);
  const [removing, setRemoving] = useState(false);

  function openCreate() {
    setEditing(null);
    setQuestion("");
    setDescription("");
    setType("single");
    setOrder("0");
    setIsActive(true);
    setOptions([{ label: "", tags: "" }]);
    setOpen(true);
  }

  function openEdit(row: SurveyQuestion) {
    setEditing(row);
    setQuestion(row.question ?? "");
    setDescription(row.description ?? "");
    setType(row.type ?? "single");
    setOrder(String(row.order ?? 0));
    setIsActive(row.is_active ?? true);
    setOptions(
      row.options && row.options.length
        ? row.options.map((o) => ({
            label: o.label ?? "",
            tags: (o.tags ?? []).map((t) => t.name).join("، "),
          }))
        : [{ label: "", tags: "" }],
    );
    setOpen(true);
  }

  function setOptionAt(index: number, patch: Partial<OptionDraft>) {
    setOptions((prev) =>
      prev.map((o, i) => (i === index ? { ...o, ...patch } : o)),
    );
  }
  function addOption() {
    setOptions((prev) => [...prev, { label: "", tags: "" }]);
  }
  function removeOption(index: number) {
    setOptions((prev) =>
      prev.length > 1 ? prev.filter((_, i) => i !== index) : prev,
    );
  }

  async function save(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const body = {
        question,
        description,
        type,
        order: Number(order),
        is_active: isActive,
        options: options
          .map((o) => ({ label: o.label.trim(), tagsRaw: o.tags }))
          .filter((o) => o.label !== "")
          .map((o) => ({
            label: o.label,
            tags: o.tagsRaw
              .split(/[,،]/)
              .map((t) => t.trim())
              .filter((t) => t !== ""),
          })),
      };
      if (editing) {
        await apiFetch(`/survey-questions/${editing.id}`, {
          method: "PUT",
          body,
        });
        toast.success("پرسش ویرایش شد.");
      } else {
        await apiFetch("/survey-questions", { method: "POST", body });
        toast.success("پرسش افزوده شد.");
      }
      setOpen(false);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
    } finally {
      setSaving(false);
    }
  }

  async function confirmDelete() {
    if (!deleting) return;
    setRemoving(true);
    try {
      await apiFetch(`/survey-questions/${deleting.id}`, { method: "DELETE" });
      toast.success("پرسش حذف شد.");
      setDeleting(null);
      reload();
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
    } finally {
      setRemoving(false);
    }
  }

  const columns: Column<SurveyQuestion>[] = [
    { key: "id", header: "شناسه", render: (r) => toFa(r.id), className: "w-20" },
    { key: "question", header: "پرسش", render: (r) => r.question ?? "—" },
    {
      key: "type",
      header: "نوع",
      render: (r) => (r.type ? TYPE_LABELS[r.type] ?? r.type : "—"),
    },
    {
      key: "order",
      header: "ترتیب",
      render: (r) => (r.order != null ? toFa(r.order) : "—"),
      className: "w-20",
    },
    {
      key: "is_active",
      header: "وضعیت",
      render: (r) => (
        <Badge tone={r.is_active ? "success" : "neutral"}>
          {r.is_active ? "فعال" : "غیرفعال"}
        </Badge>
      ),
    },
  ];

  return (
    <div>
      <PageHeader
        title="پرسش‌های نظرسنجی"
        subtitle="مدیریت پرسش‌ها و گزینه‌های نظرسنجی"
        action={
          <Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
            پرسش جدید
          </Button>
        }
      />

      <DataTable
        columns={columns}
        rows={data}
        loading={loading}
        error={error}
        onRetry={reload}
        emptyMessage="هنوز پرسش نظرسنجی‌ای ثبت نشده است."
        emptyAction={
          <Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
            پرسش جدید
          </Button>
        }
        actions={(row) => (
          <>
            <Button
              variant="ghost"
              onClick={() => openEdit(row)}
              aria-label="ویرایش"
            >
              <EditIcon className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              onClick={() => setDeleting(row)}
              aria-label="حذف"
              className="text-danger"
            >
              <TrashIcon className="h-4 w-4" />
            </Button>
          </>
        )}
      />

      <Modal
        open={open}
        onClose={() => setOpen(false)}
        title={editing ? "ویرایش پرسش" : "پرسش جدید"}
        footer={
          <>
            <Button variant="secondary" onClick={() => setOpen(false)}>
              انصراف
            </Button>
            <Button form="survey-form" type="submit" loading={saving}>
              ذخیره
            </Button>
          </>
        }
      >
        <form id="survey-form" onSubmit={save} className="flex flex-col gap-4">
          <Field label="پرسش" required>
            <Input
              value={question}
              onChange={(e) => setQuestion(e.target.value)}
              placeholder="متن پرسش"
              required
              autoFocus
            />
          </Field>

          <Field label="توضیحات">
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="توضیحات تکمیلی (اختیاری)"
            />
          </Field>

          <Field label="نوع" required>
            <Select value={type} onChange={(e) => setType(e.target.value)}>
              <option value="single">تک‌گزینه</option>
              <option value="multiple">چندگزینه</option>
            </Select>
          </Field>

          <Field label="ترتیب">
            <Input
              type="number"
              value={order}
              onChange={(e) => setOrder(e.target.value)}
              dir="ltr"
            />
          </Field>

          <Switch checked={isActive} onChange={setIsActive} label="فعال" />

          <div className="flex flex-col gap-2">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-foreground">
                گزینه‌ها
              </span>
              <Button
                type="button"
                variant="ghost"
                onClick={addOption}
                icon={<PlusIcon className="h-4 w-4" />}
              >
                افزودن گزینه
              </Button>
            </div>
            {options.map((opt, i) => (
              <div
                key={i}
                className="flex items-start gap-2 rounded-lg border border-border p-2"
              >
                <div className="flex flex-1 flex-col gap-2">
                  <Input
                    value={opt.label}
                    onChange={(e) => setOptionAt(i, { label: e.target.value })}
                    placeholder={`گزینه ${toFa(i + 1)}`}
                  />
                  <Input
                    value={opt.tags}
                    onChange={(e) => setOptionAt(i, { tags: e.target.value })}
                    placeholder="برچسب‌ها (با کاما جدا کنید) — برای پیشنهاد محتوا"
                  />
                </div>
                <Button
                  type="button"
                  variant="ghost"
                  onClick={() => removeOption(i)}
                  aria-label="حذف گزینه"
                  className="text-danger"
                  disabled={options.length <= 1}
                >
                  <TrashIcon className="h-4 w-4" />
                </Button>
              </div>
            ))}
          </div>
        </form>
      </Modal>

      <ConfirmDialog
        open={!!deleting}
        message={`آیا از حذف «${deleting?.question ?? ""}» مطمئن هستید؟`}
        loading={removing}
        onConfirm={confirmDelete}
        onClose={() => setDeleting(null)}
      />
    </div>
  );
}
