"use client";

import { useState } from "react";
import { ArrowUpRight, ShieldCheck } from "lucide-react";
import type { ConsentAcceptedMap, ConsentLocale, StepConsentData } from "@/lib/api-types";
import { t } from "@/lib/i18n/wizard-labels";
import { useReferenceOptions, type ReferenceOption } from "../hooks/useReferenceOptions";

interface Props {
  data: Partial<StepConsentData>;
  loading: boolean;
  onSave: (data: StepConsentData) => Promise<unknown>;
  onSaveDraft: (data: Partial<StepConsentData>) => Promise<unknown>;
}

function isRequiredConsent(consent: ReferenceOption): boolean {
  return consent.metadata?.required !== false;
}

export default function StepConsent({ data, loading, onSave }: Props) {
  const [locale, setLocale] = useState<ConsentLocale>(data?.locale ?? "uz");
  const { options: consents, loading: optionsLoading, error: optionsError } = useReferenceOptions(
    "consent_types",
    "UZ",
    { locale },
  );
  const [accepted, setAccepted] = useState<Record<string, boolean>>(data?.accepted ?? {});

  const requiredConsents = consents.filter(isRequiredConsent);
  const allAccepted =
    requiredConsents.length > 0 && requiredConsents.every((consent) => accepted[consent.value]);

  const toggle = (key: string) => {
    setAccepted((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  const handleContinue = () => {
    const acceptedPayload: Record<string, boolean> = {};
    for (const consent of requiredConsents) {
      acceptedPayload[consent.value] = !!accepted[consent.value];
    }

    onSave({
      accepted: acceptedPayload as ConsentAcceptedMap,
      consentVersion: "1.0.0",
      consentType: requiredConsents[0]?.value ?? "credit_check",
      acceptedAt: new Date().toISOString(),
      locale,
    });
  };

  return (
    <div className="space-y-5">
      <div>
        <h2 className="font-onest text-2xl font-semibold text-ink">{t("consent.title", locale)}</h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">{t("consent.subtitle", locale)}</p>
      </div>

      <div>
        <label htmlFor="consent-locale" className="block font-inter text-sm font-medium text-ink-soft mb-1.5">
          {t("consent.localeLabel", locale)}
        </label>
        <select
          id="consent-locale"
          value={locale}
          onChange={(e) => setLocale(e.target.value as ConsentLocale)}
          className="w-full px-4 py-3 rounded-xl border border-border bg-surface font-inter text-sm text-ink focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20 transition-colors appearance-none cursor-pointer"
        >
          <option value="uz">O'zbekcha</option>
          <option value="ru">Русский</option>
        </select>
      </div>

      <div className="rounded-2xl border border-green-deep/15 bg-green-deep/5 p-5 flex items-start gap-3">
        <ShieldCheck className="w-5 h-5 text-green-deep mt-0.5 shrink-0" />
        <p className="font-inter text-sm text-ink-soft leading-relaxed">
          {t("consent.privacyNote", locale)}
        </p>
      </div>

      {optionsError && (
        <div className="rounded-xl border border-red-200 bg-red-50 dark:border-red-700/30 dark:bg-red-900/20 px-4 py-3 text-sm text-red-700 dark:text-red-400 font-inter">
          {optionsError}
        </div>
      )}

      <div className="space-y-3">
        {consents.map((consent) => (
          <label
            key={consent.value}
            className="flex items-start gap-3 p-4 rounded-xl border border-border bg-surface hover:border-green-deep/20 transition-colors cursor-pointer"
          >
            <input
              type="checkbox"
              checked={!!accepted[consent.value]}
              onChange={() => toggle(consent.value)}
              className="mt-0.5 w-5 h-5 rounded border-border text-green-deep focus:ring-green-deep/20 cursor-pointer"
            />
            <span className="font-inter text-sm text-ink-soft leading-relaxed">
              {consent.label}
            </span>
          </label>
        ))}
      </div>

      <button
        onClick={handleContinue}
        disabled={!allAccepted || loading || optionsLoading}
        className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
      >
        {loading ? t("common.saving", locale) : t("consent.acceptContinue", locale)}
        <ArrowUpRight className="w-4 h-4" />
      </button>
    </div>
  );
}
