"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface Props {
  readingId: string;
  initialTitle: string;
  initialSections: string;
  initialAdvice: string;
  initialSummary: string;
  followUpQuestion: string | null;
  initialFollowUpSections: string;
  initialFollowUpAdvice: string;
  initialFollowUpSummary: string;
}

export function ManualAnswerForm(props: Props) {
  const router = useRouter();
  const [main, setMain] = useState({
    title: props.initialTitle,
    sections: props.initialSections,
    advice: props.initialAdvice,
    summary: props.initialSummary,
  });
  const [follow, setFollow] = useState({
    sections: props.initialFollowUpSections,
    advice: props.initialFollowUpAdvice,
    summary: props.initialFollowUpSummary,
  });
  const [savingMain, setSavingMain] = useState(false);
  const [savingFollow, setSavingFollow] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function saveMain() {
    setError(null);
    setSavingMain(true);
    try {
      const res = await fetch(`/api/admin/readings/${props.readingId}/answer`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          main: {
            title: main.title,
            sections: main.sections,
            advice: main.advice,
            summary: main.summary,
          },
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error ?? "خطا در ذخیره پاسخ");
      }
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "خطا در ذخیره پاسخ");
    } finally {
      setSavingMain(false);
    }
  }

  async function saveFollow() {
    setError(null);
    setSavingFollow(true);
    try {
      const res = await fetch(`/api/admin/readings/${props.readingId}/answer`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          followUp: {
            sections: follow.sections,
            advice: follow.advice,
            summary: follow.summary,
          },
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error ?? "خطا در ذخیره پاسخ پیگیری");
      }
      router.refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : "خطا در ذخیره پاسخ پیگیری");
    } finally {
      setSavingFollow(false);
    }
  }

  return (
    <div className="space-y-6">
      {error && <p className="text-sm text-destructive">{error}</p>}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">ثبت پاسخ دستی فال اصلی</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <Input
            placeholder="عنوان"
            value={main.title}
            onChange={(e) => setMain((p) => ({ ...p, title: e.target.value }))}
          />
          <textarea
            className="w-full min-h-36 rounded-md border p-3 text-sm"
            placeholder="تفسیر"
            value={main.sections}
            onChange={(e) => setMain((p) => ({ ...p, sections: e.target.value }))}
          />
          <textarea
            className="w-full min-h-20 rounded-md border p-3 text-sm"
            placeholder="پند"
            value={main.advice}
            onChange={(e) => setMain((p) => ({ ...p, advice: e.target.value }))}
          />
          <textarea
            className="w-full min-h-20 rounded-md border p-3 text-sm"
            placeholder="خلاصه"
            value={main.summary}
            onChange={(e) => setMain((p) => ({ ...p, summary: e.target.value }))}
          />
          <Button onClick={saveMain} disabled={savingMain}>
            {savingMain ? "در حال ذخیره..." : "ذخیره پاسخ فال اصلی"}
          </Button>
        </CardContent>
      </Card>

      {props.followUpQuestion && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">ثبت پاسخ دستی سوال پیگیری</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <p className="text-sm text-muted-foreground">
              سوال کاربر: {props.followUpQuestion}
            </p>
            <textarea
              className="w-full min-h-36 rounded-md border p-3 text-sm"
              placeholder="تفسیر پیگیری"
              value={follow.sections}
              onChange={(e) => setFollow((p) => ({ ...p, sections: e.target.value }))}
            />
            <textarea
              className="w-full min-h-20 rounded-md border p-3 text-sm"
              placeholder="پند پیگیری"
              value={follow.advice}
              onChange={(e) => setFollow((p) => ({ ...p, advice: e.target.value }))}
            />
            <textarea
              className="w-full min-h-20 rounded-md border p-3 text-sm"
              placeholder="خلاصه پیگیری"
              value={follow.summary}
              onChange={(e) => setFollow((p) => ({ ...p, summary: e.target.value }))}
            />
            <Button onClick={saveFollow} disabled={savingFollow}>
              {savingFollow ? "در حال ذخیره..." : "ذخیره پاسخ پیگیری"}
            </Button>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
