"use client";

import { Plus, Sparkles, Trash2 } from "lucide-react";
import { Modal } from "@/components/ui/Modal";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Field, Label } from "@/components/ui/Card";
import {
  THANK_YOU_EMOJI_CHOICES,
  buildGoodBadThankYouVariants,
  emptyThankYouVariant,
  getThankYouConditionOptions,
  normalizeThankYouConfig,
} from "@/lib/utils/thank-you-screen";
import { cn } from "@/lib/utils/cn";
import type { ThankYouScreenConfig, ThankYouVariant } from "@/types";
import type { BuilderQuestion } from "@/types/builder";

interface SurveyThankYouPanelProps {
  open: boolean;
  onClose: () => void;
  questions: BuilderQuestion[];
  config: ThankYouScreenConfig;
  onChange: (next: ThankYouScreenConfig) => void;
  saving?: boolean;
}

export function SurveyThankYouPanel({
  open,
  onClose,
  questions,
  config,
  onChange,
  saving,
}: SurveyThankYouPanelProps) {
  const normalized = normalizeThankYouConfig(config);
  const variants = normalized.variants ?? [];
  const scoredQuestion = questions.find(
    (q) => q.type === "nps" || q.type === "rating"
  );
  const usableQuestions = questions.filter(
    (q) =>
      q.type === "nps" ||
      q.type === "rating" ||
      q.type === "multiple_choice" ||
      q.type === "dropdown" ||
      q.type === "checkbox"
  );

  function patch(partial: Partial<ThankYouScreenConfig>) {
    onChange({ ...normalized, ...partial });
  }

  function patchVariant(id: string, partial: Partial<ThankYouVariant>) {
    patch({
      variants: variants.map((v) => (v.id === id ? { ...v, ...partial } : v)),
    });
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="What should people see at the end?"
      description="Show one default message, or a different emoji and text when the answer is good or bad."
      maxWidthClassName="max-w-[640px]"
    >
      <EndingPreview
        emoji={normalized.emoji ?? "✅"}
        title={normalized.title ?? "Thank you!"}
        description={normalized.description ?? ""}
        label="Default ending"
      />

      <p className="mb-2 mt-5 text-[13px] font-bold">Default message</p>
      <p className="mb-3 text-[12px] text-muted">
        Everyone sees this unless a rule below matches their answer.
      </p>
      <EmojiPicker
        value={normalized.emoji ?? "✅"}
        onChange={(emoji) => patch({ emoji })}
      />
      <Field>
        <Label htmlFor="ty-title">Headline</Label>
        <Input
          id="ty-title"
          value={normalized.title ?? ""}
          onChange={(e) => patch({ title: e.target.value })}
          placeholder="Thank you!"
        />
      </Field>
      <Field>
        <Label htmlFor="ty-desc">Message</Label>
        <textarea
          id="ty-desc"
          className="min-h-[72px] w-full resize-y rounded-[10px] border-[1.5px] border-border p-3 text-sm focus:border-primary focus:outline-none"
          value={normalized.description ?? ""}
          onChange={(e) => patch({ description: e.target.value })}
          placeholder="Your response has been recorded."
        />
      </Field>

      <div className="mb-2 mt-2 flex flex-wrap items-center justify-between gap-2">
        <p className="text-[13px] font-bold">Different ending based on an answer</p>
        <div className="flex flex-wrap gap-1.5">
          {scoredQuestion && (
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => {
                const presets = buildGoodBadThankYouVariants(questions);
                const questionId = presets[0]?.questionId;
                const already = variants.some(
                  (v) =>
                    v.questionId === questionId &&
                    (v.conditionValue === "9-10" ||
                      v.conditionValue === "0-6" ||
                      v.emoji === "🎉" ||
                      v.emoji === "😔")
                );
                if (already || presets.length === 0) return;
                patch({ variants: [...variants, ...presets] });
              }}
            >
              <Sparkles className="mr-1 h-3.5 w-3.5" />
              Add Good vs Bad
            </Button>
          )}
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={usableQuestions.length === 0}
            onClick={() => {
              const q = usableQuestions[0];
              if (!q) return;
              patch({
                variants: [...variants, emptyThankYouVariant(q.id, q)],
              });
            }}
          >
            <Plus className="mr-1 h-3.5 w-3.5" />
            Add rule
          </Button>
        </div>
      </div>

      {usableQuestions.length === 0 && (
        <p className="rounded-[10px] border border-dashed border-border bg-[#F8FAFC] px-4 py-5 text-center text-[13px] text-muted">
          Add an NPS, rating, or multiple-choice question first, then you can
          show a different ending for happy vs unhappy answers.
        </p>
      )}

      <div className="space-y-3">
        {variants.map((variant, index) => {
          const question =
            questions.find((q) => q.id === variant.questionId) ??
            usableQuestions[0];
          const options = getThankYouConditionOptions(question);
          return (
            <div
              key={variant.id}
              className="rounded-[12px] border border-border p-3.5"
            >
              <div className="mb-3 flex items-center justify-between gap-2">
                <span className="text-[11px] font-bold uppercase tracking-wide text-muted">
                  Rule {index + 1} · first match wins
                </span>
                <button
                  type="button"
                  className="rounded-[6px] p-1 text-muted hover:bg-[#FFF5F5] hover:text-danger"
                  onClick={() =>
                    patch({
                      variants: variants.filter((v) => v.id !== variant.id),
                    })
                  }
                  aria-label="Remove rule"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>

              <div className="mb-3 grid gap-2 sm:grid-cols-2">
                <Field className="mb-0">
                  <Label>If this question</Label>
                  <Select
                    value={variant.questionId}
                    onChange={(e) => {
                      const nextQ = questions.find((q) => q.id === e.target.value);
                      const nextOptions = getThankYouConditionOptions(nextQ);
                      patchVariant(variant.id, {
                        questionId: e.target.value,
                        conditionType: "equals",
                        conditionValue: nextOptions[0]?.value ?? null,
                      });
                    }}
                  >
                    {usableQuestions.map((q, i) => (
                      <option key={q.id} value={q.id}>
                        Q{questions.findIndex((x) => x.id === q.id) + 1}.{" "}
                        {q.title || `Question ${i + 1}`}
                      </option>
                    ))}
                  </Select>
                </Field>
                <Field className="mb-0">
                  <Label>is</Label>
                  <Select
                    value={
                      variant.conditionType === "any_answer"
                        ? "any_answer"
                        : (variant.conditionValue ?? "")
                    }
                    onChange={(e) => {
                      const val = e.target.value;
                      if (val === "any_answer") {
                        patchVariant(variant.id, {
                          conditionType: "any_answer",
                          conditionValue: null,
                        });
                        return;
                      }
                      patchVariant(variant.id, {
                        conditionType: "equals",
                        conditionValue: val,
                      });
                    }}
                  >
                    <option value="any_answer">Any answer</option>
                    {options.map((opt) => (
                      <option key={opt.value} value={opt.value}>
                        {opt.label}
                      </option>
                    ))}
                  </Select>
                </Field>
              </div>

              <EndingPreview
                emoji={variant.emoji}
                title={variant.title}
                description={variant.description}
                compact
              />
              <div className="mt-3">
                <EmojiPicker
                  value={variant.emoji}
                  onChange={(emoji) => patchVariant(variant.id, { emoji })}
                />
                <Input
                  className="mb-2"
                  value={variant.title}
                  onChange={(e) =>
                    patchVariant(variant.id, { title: e.target.value })
                  }
                  placeholder="Headline"
                />
                <textarea
                  className="min-h-[64px] w-full resize-y rounded-[10px] border-[1.5px] border-border p-3 text-sm focus:border-primary focus:outline-none"
                  value={variant.description}
                  onChange={(e) =>
                    patchVariant(variant.id, { description: e.target.value })
                  }
                  placeholder="Message"
                />
              </div>
            </div>
          );
        })}
      </div>

      <div className="mt-5 flex justify-end">
        <Button type="button" onClick={onClose} loading={saving}>
          Done
        </Button>
      </div>
    </Modal>
  );
}

function EmojiPicker({
  value,
  onChange,
}: {
  value: string;
  onChange: (emoji: string) => void;
}) {
  return (
    <div className="mb-3 flex flex-wrap gap-1.5">
      {THANK_YOU_EMOJI_CHOICES.map((emoji) => (
        <button
          key={emoji}
          type="button"
          onClick={() => onChange(emoji)}
          className={cn(
            "flex h-9 w-9 items-center justify-center rounded-[9px] border text-lg",
            value === emoji
              ? "border-primary bg-[#EFF6FF]"
              : "border-border hover:border-accent"
          )}
          aria-label={`Use ${emoji}`}
        >
          {emoji}
        </button>
      ))}
    </div>
  );
}

function EndingPreview({
  emoji,
  title,
  description,
  label,
  compact,
}: {
  emoji: string;
  title: string;
  description: string;
  label?: string;
  compact?: boolean;
}) {
  return (
    <div
      className={cn(
        "rounded-[12px] border border-border bg-[#F8FAFC] text-center",
        compact ? "px-3 py-3" : "px-4 py-5"
      )}
    >
      {label && (
        <div className="mb-2 text-[10.5px] font-bold uppercase tracking-wide text-muted">
          {label}
        </div>
      )}
      <div className={cn(compact ? "text-2xl" : "text-4xl")}>{emoji}</div>
      <div className="mt-2 text-[14px] font-bold">{title || "Thank you!"}</div>
      <p className="mt-1 text-[12.5px] text-muted">
        {description || "Your response has been recorded."}
      </p>
    </div>
  );
}
