"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/Button";
import { Toggle } from "@/components/ui/Toggle";
import { Card, CardHeader, CardTitle } from "@/components/ui/Card";
import {
  ParticipantProfileFields,
  type ParticipantProfileValues,
} from "@/components/features/participant/ParticipantProfileFields";
import {
  changeConsent,
  closeParticipantProfile,
  setParticipationPaused,
  updateParticipantProfile,
} from "@/lib/actions/participant";
import { swalConfirm, swalToast } from "@/lib/utils/swal";
import type { ConsentView } from "@/lib/queries/participant-queries";

interface ParticipantSettingsProps {
  profile: ParticipantProfileValues;
  paused: boolean;
  consents: ConsentView[];
}

export function ParticipantSettings({
  profile: initialProfile,
  paused,
  consents,
}: ParticipantSettingsProps) {
  const router = useRouter();
  const { update } = useSession();
  const [profile, setProfile] = useState(initialProfile);
  const [saving, setSaving] = useState(false);
  const [busyKey, setBusyKey] = useState<string | null>(null);

  async function saveProfile() {
    setSaving(true);
    const result = await updateParticipantProfile({
      countryCode: profile.countryCode,
      regionCode: profile.regionCode,
      ageBand: profile.ageBand as never,
    });
    setSaving(false);
    void swalToast.fire({
      icon: result.success ? "success" : "error",
      title: result.success ? "Profile saved" : result.error,
    });
    if (result.success) router.refresh();
  }

  async function toggleConsent(c: ConsentView, grant: boolean) {
    if (!grant) {
      const ok = await swalConfirm({
        title: `Turn off “${c.title}”?`,
        text: "We'll stop using your data for this purpose from now on. Answers already given are kept until their retention period ends.",
        confirmText: "Turn off",
        danger: true,
      });
      if (!ok) return;
    }
    setBusyKey(c.key);
    const result = await changeConsent({ policyKey: c.key, grant });
    setBusyKey(null);
    if (!result.success) {
      void swalToast.fire({ icon: "error", title: result.error });
      return;
    }
    router.refresh();
  }

  async function togglePause() {
    setBusyKey("pause");
    const result = await setParticipationPaused(!paused);
    setBusyKey(null);
    if (!result.success) {
      void swalToast.fire({ icon: "error", title: result.error });
      return;
    }
    router.refresh();
  }

  async function handleClose() {
    const ok = await swalConfirm({
      title: "Close your participant profile?",
      text: "You'll stop receiving questions and invitations. Your account and any creator workspace stay intact. You can rejoin later.",
      confirmText: "Close profile",
      danger: true,
    });
    if (!ok) return;
    setBusyKey("close");
    const result = await closeParticipantProfile();
    if (!result.success) {
      setBusyKey(null);
      void swalToast.fire({ icon: "error", title: result.error });
      return;
    }
    await update({});
    window.location.assign(result.data!.redirectTo);
  }

  return (
    <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
      <Card>
        <CardHeader>
          <CardTitle>Participant profile</CardTitle>
        </CardHeader>
        <div className="p-5">
          <ParticipantProfileFields values={profile} onChange={setProfile} />
          <Button
            type="button"
            loading={saving}
            disabled={!profile.countryCode || !profile.ageBand}
            onClick={saveProfile}
          >
            Save profile
          </Button>
        </div>
      </Card>

      <div className="space-y-4">
        <Card>
          <div id="permissions" />
          <CardHeader>
            <CardTitle>Permissions</CardTitle>
          </CardHeader>
          <ul className="divide-y divide-border">
            {consents.map((c) => (
              <li key={c.key} className="flex items-start justify-between gap-4 px-5 py-4">
                <div className="min-w-0">
                  <div className="text-[13.5px] font-bold">
                    {c.title}
                    <span className="ml-2 text-[11px] font-semibold text-muted">
                      v{c.version}
                      {c.isRequired ? " · required" : " · optional"}
                    </span>
                  </div>
                  <p className="mt-0.5 text-[12.5px] text-muted">{c.purpose}</p>
                  <details className="mt-1.5 text-[12px] text-muted">
                    <summary className="cursor-pointer font-semibold text-primary">
                      Read full text
                    </summary>
                    <p className="mt-1.5 whitespace-pre-line">{c.policyText}</p>
                    {c.retentionDays && (
                      <p className="mt-1">Retention: {c.retentionDays} days.</p>
                    )}
                  </details>
                  {c.decidedAt && (
                    <p className="mt-1 text-[11px] text-muted">
                      {c.granted ? "Granted" : "Turned off"}{" "}
                      {new Date(c.decidedAt).toLocaleString()}
                    </p>
                  )}
                </div>
                <Toggle
                  checked={c.granted}
                  disabled={c.isRequired || busyKey === c.key}
                  onChange={(next) => toggleConsent(c, next)}
                />
              </li>
            ))}
          </ul>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Participation</CardTitle>
          </CardHeader>
          <div className="space-y-4 p-5">
            <div className="flex items-start justify-between gap-4">
              <div>
                <div className="text-[13.5px] font-bold">
                  {paused ? "Participation paused" : "Taking part"}
                </div>
                <p className="text-[12.5px] text-muted">
                  Pause to stop receiving questions without closing your profile.
                </p>
              </div>
              <Button
                type="button"
                variant="outline"
                size="sm"
                loading={busyKey === "pause"}
                onClick={togglePause}
              >
                {paused ? "Resume" : "Pause"}
              </Button>
            </div>
            <div className="flex items-start justify-between gap-4 border-t border-border pt-4">
              <div>
                <div className="text-[13.5px] font-bold text-danger">
                  Close participant profile
                </div>
                <p className="text-[12.5px] text-muted">
                  Leaves the participant panel. Your login stays active.
                </p>
              </div>
              <Button
                type="button"
                variant="danger"
                size="sm"
                loading={busyKey === "close"}
                onClick={handleClose}
              >
                Close
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}
