import { useState } from "react";
import { Linking, Pressable, StyleSheet, Text, View } from "react-native";
import { Body, Button, Screen, Small, Title } from "@/components/ui";
import type { TextStyle } from "react-native";
import { acceptConsent } from "@/lib/api";
import { t } from "@/lib/i18n";
import { colors, spacing, typography } from "@/lib/theme";

interface ConsentScreenProps {
  onAccepted: () => void;
}

export function ConsentScreen({ onAccepted }: ConsentScreenProps) {
  const [checked, setChecked] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const openUrl = (url: string) => {
    void Linking.openURL(url);
  };

  const submit = async () => {
    if (!checked) return;
    setBusy(true);
    setError(null);
    try {
      await acceptConsent();
      onAccepted();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("common.error"));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Screen style={{ justifyContent: "space-between" }}>
      <View style={{ gap: spacing.md, paddingTop: spacing.lg }}>
        <Title>{t("consent.title")}</Title>
        <Body>{t("consent.body")}</Body>
        <View style={{ gap: spacing.sm, paddingTop: spacing.sm }}>
          <Pressable onPress={() => openUrl("https://cibello.app/villkor.html")}>
            <Text style={[typography.body, styles.link]}>{t("consent.termsLink")}</Text>
          </Pressable>
          <Pressable onPress={() => openUrl("https://cibello.app/integritet.html")}>
            <Text style={[typography.body, styles.link]}>{t("consent.privacyLink")}</Text>
          </Pressable>
        </View>
      </View>

      <View style={{ gap: spacing.md, paddingBottom: spacing.lg }}>
        <Pressable onPress={() => setChecked((v) => !v)} style={styles.checkboxRow}>
          <View style={[styles.box, checked && styles.boxChecked]}>
            {checked && <Text style={styles.checkmark}>✓</Text>}
          </View>
          <Body>{t("consent.checkbox")}</Body>
        </Pressable>

        {error && <Small style={{ color: colors.danger }}>{error}</Small>}

        <Button
          label={t("consent.submit")}
          onPress={() => void submit()}
          disabled={!checked}
          loading={busy}
        />
      </View>
    </Screen>
  );
}

const styles = StyleSheet.create({
  link: {
    color: colors.primaryDark,
    textDecorationLine: "underline",
  },
  checkboxRow: {
    flexDirection: "row",
    alignItems: "flex-start",
    gap: spacing.sm,
  },
  box: {
    width: 22,
    height: 22,
    borderRadius: 4,
    borderWidth: 2,
    borderColor: colors.primary,
    alignItems: "center",
    justifyContent: "center",
    marginTop: 2,
  },
  boxChecked: {
    backgroundColor: colors.primary,
  },
  checkmark: {
    color: "#fff",
    fontSize: 14,
    fontWeight: "700",
  },
  checkboxLabel: {
    flex: 1,
  },
});
