"use client";

import { useParams } from "next/navigation";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useTenantId } from "@/hooks/useTenantId";
import { experienceApi } from "@/modules/experience/services/experience-api";
import { ExperiencePageLoader, ExperiencePageError } from "@/modules/experience/pages/shared";
import { ExperienceDetailBreadcrumbs } from "@/modules/experience/components/ExperienceBreadcrumbs";
import { PageHeader, Button, Card, CardContent, FormField } from "@/components/ds";

export const SurveyBuilderPage = function ExperienceSurveyBuilder() {
  const params = useParams();
  const surveyId = String(params.id);
  const { tenantId } = useTenantId();
  const qc = useQueryClient();

  const surveyQ = useQuery({
    queryKey: ["experience", tenantId, "survey", surveyId],
    queryFn: () => experienceApi.surveys.get(tenantId!, surveyId),
    enabled: !!tenantId && !!surveyId,
  });

  const saveM = useMutation({
    mutationFn: (schema: string) =>
      experienceApi.surveys.update(tenantId!, surveyId, {
        survey_schema_json: JSON.parse(schema),
        version: surveyQ.data?.version,
      }),
    onSuccess: () => {
      toast.success("اسکیمای نظرسنجی ذخیره شد");
      qc.invalidateQueries({ queryKey: ["experience", tenantId, "survey", surveyId] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!tenantId || surveyQ.isLoading) return <ExperiencePageLoader />;
  if (surveyQ.error) return <ExperiencePageError error={surveyQ.error} onRetry={() => surveyQ.refetch()} />;

  const survey = surveyQ.data!;
  const schemaStr = JSON.stringify(survey.survey_schema_json ?? { questions: [] }, null, 2);

  return (
    <div className="space-y-4">
      <ExperienceDetailBreadcrumbs parent="نظرسنجی‌ها" parentHref="/experience/surveys" current={String(survey.name ?? survey.code)} />
      <PageHeader title={`سازنده نظرسنجی: ${String(survey.name ?? survey.code)}`} />
      <Card>
        <CardContent className="space-y-4 p-4">
          <FormField label="اسکیمای JSON">
            <textarea id="survey-schema" className="min-h-[320px] w-full rounded-xl border p-3 font-mono text-xs" defaultValue={schemaStr} />
          </FormField>
          <Button
            onClick={() => {
              const el = document.getElementById("survey-schema") as HTMLTextAreaElement;
              try {
                JSON.parse(el.value);
                saveM.mutate(el.value);
              } catch {
                toast.error("JSON نامعتبر");
              }
            }}
            loading={saveM.isPending}
          >
            ذخیره
          </Button>
        </CardContent>
      </Card>
    </div>
  );
};

export default SurveyBuilderPage;
