"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { createClient } from "@/lib/supabase/client";
import { Card, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input, Label, Select, FieldError } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal";
import { Badge } from "@/components/ui/badge";
import { settingsProfileSchema, resetPasswordSchema } from "@/lib/validation/schemas";
import { useTranslations, useLocale } from "@/lib/i18n/i18n-provider";
import { PLANS } from "@/lib/pricing";
import type { Profile, UserSettings, Locale } from "@/types/database";

export function SettingsView({
  profile,
  settings,
  email
}: {
  profile: Profile | null;
  settings: UserSettings | null;
  email: string;
}) {
  const t = useTranslations();
  const locale = useLocale();
  const router = useRouter();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [portalLoading, setPortalLoading] = useState(false);

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm({
    resolver: zodResolver(settingsProfileSchema),
    defaultValues: {
      firstName: profile?.first_name ?? "",
      currency: profile?.currency ?? "PLN",
      preferredLanguage: (profile?.preferred_language ?? locale) as Locale
    }
  });

  async function onSubmitProfile(values: any) {
    const supabase = createClient();
    const { data: userData } = await supabase.auth.getUser();
    if (!userData.user) return;
    await supabase
      .from("profiles")
      .update({
        first_name: values.firstName,
        currency: values.currency,
        preferred_language: values.preferredLanguage
      })
      .eq("id", userData.user.id);

    if (values.preferredLanguage !== locale) {
      document.cookie = `tidyly-locale=${values.preferredLanguage};path=/;max-age=31536000`;
      router.push(`/${values.preferredLanguage}/settings`);
      router.refresh();
    } else {
      router.refresh();
    }
  }

  async function toggleNotification(key: keyof UserSettings, value: boolean) {
    const supabase = createClient();
    const { data: userData } = await supabase.auth.getUser();
    if (!userData.user) return;
    await supabase.from("user_settings").update({ [key]: value }).eq("user_id", userData.user.id);
    router.refresh();
  }

  async function openBillingPortal() {
    setPortalLoading(true);
    try {
      const res = await fetch("/api/stripe/portal", { method: "POST" });
      const data = await res.json();
      if (data.url) window.location.href = data.url;
    } finally {
      setPortalLoading(false);
    }
  }

  async function handleDeleteAccount() {
    // Deleting an auth.users row (and cascading all owned data) requires
    // the service role key, so this calls a server route rather than the
    // browser client. See src/app/api/account/delete/route.ts.
    await fetch("/api/account/delete", { method: "POST" });
    const supabase = createClient();
    await supabase.auth.signOut();
    router.push(`/${locale}`);
  }

  const plan = profile?.subscription_plan ?? "free";

  return (
    <div className="max-w-2xl space-y-6">
      {/* Profile */}
      <Card>
        <CardHeader>
          <CardTitle>{t("settings.profile")}</CardTitle>
        </CardHeader>
        <form onSubmit={handleSubmit(onSubmitProfile)} className="space-y-4">
          <div>
            <Label htmlFor="firstName">{t("settings.firstName")}</Label>
            <Input id="firstName" error={errors.firstName?.message as string} {...register("firstName")} />
            <FieldError>{errors.firstName?.message as string}</FieldError>
          </div>
          <div>
            <Label htmlFor="email">{t("settings.email")}</Label>
            <Input id="email" value={email} disabled />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Label htmlFor="preferredLanguage">{t("settings.language")}</Label>
              <Select id="preferredLanguage" {...register("preferredLanguage")}>
                <option value="en">English</option>
                <option value="pl">Polski</option>
              </Select>
            </div>
            <div>
              <Label htmlFor="currency">{t("settings.currency")}</Label>
              <Select id="currency" {...register("currency")}>
                <option value="PLN">PLN</option>
                <option value="EUR">EUR</option>
                <option value="USD">USD</option>
                <option value="GBP">GBP</option>
              </Select>
            </div>
          </div>
          <Button type="submit" loading={isSubmitting}>
            {t("common.save")}
          </Button>
        </form>
      </Card>

      {/* Notifications */}
      <Card>
        <CardHeader>
          <CardTitle>{t("settings.notifications")}</CardTitle>
        </CardHeader>
        <div className="space-y-3">
          <ToggleRow
            label="Email notifications"
            checked={settings?.email_notifications ?? true}
            onChange={(v) => toggleNotification("email_notifications", v)}
          />
          <ToggleRow
            label="Budget alerts"
            checked={settings?.budget_alerts ?? true}
            onChange={(v) => toggleNotification("budget_alerts", v)}
          />
          <ToggleRow
            label="Subscription reminders"
            checked={settings?.subscription_reminders ?? true}
            onChange={(v) => toggleNotification("subscription_reminders", v)}
          />
          <ToggleRow
            label="Goal updates"
            checked={settings?.goal_updates ?? true}
            onChange={(v) => toggleNotification("goal_updates", v)}
          />
        </div>
      </Card>

      {/* Subscription */}
      <Card>
        <CardHeader>
          <CardTitle>{t("settings.subscription")}</CardTitle>
        </CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm text-ink-500">{t("billing.currentPlan")}</p>
            <p className="text-lg font-semibold capitalize text-ink-900">{plan}</p>
          </div>
          <Badge tone={profile?.subscription_status === "active" ? "success" : "neutral"}>
            {t(`billing.status.${profile?.subscription_status ?? "free"}`)}
          </Badge>
        </div>
        <div className="mt-4 flex gap-2">
          {plan === "free" ? (
            <Button onClick={() => router.push(`/${locale}#pricing`)}>{t("billing.upgrade")}</Button>
          ) : (
            <Button variant="secondary" onClick={openBillingPortal} loading={portalLoading}>
              {t("billing.manageBilling")}
            </Button>
          )}
        </div>
      </Card>

      {/* Security */}
      <SecurityCard />

      {/* Delete account */}
      <Card className="border-red-100">
        <CardHeader>
          <CardTitle className="text-red-700">{t("settings.deleteAccount")}</CardTitle>
        </CardHeader>
        <p className="text-sm text-ink-500">{t("settings.deleteWarning")}</p>
        <Button variant="danger" className="mt-4" onClick={() => setDeleteOpen(true)}>
          {t("settings.deleteAccount")}
        </Button>
      </Card>

      <Modal open={deleteOpen} onClose={() => setDeleteOpen(false)} title={t("settings.deleteAccount")}>
        <p className="text-sm text-ink-600">{t("settings.deleteWarning")}</p>
        <div className="mt-6 flex justify-end gap-2">
          <Button variant="secondary" onClick={() => setDeleteOpen(false)}>
            {t("common.cancel")}
          </Button>
          <Button variant="danger" onClick={handleDeleteAccount}>
            {t("common.confirm")}
          </Button>
        </div>
      </Modal>
    </div>
  );
}

function ToggleRow({
  label,
  checked,
  onChange
}: {
  label: string;
  checked: boolean;
  onChange: (v: boolean) => void;
}) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-sm text-ink-700">{label}</span>
      <button
        role="switch"
        aria-checked={checked}
        aria-label={label}
        onClick={() => onChange(!checked)}
        className="relative h-6 w-11 rounded-full bg-ink-200 transition-colors data-[on=true]:bg-brand-600"
        data-on={checked}
      >
        <span
          className={`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${
            checked ? "translate-x-[22px]" : "translate-x-0.5"
          }`}
        />
      </button>
    </div>
  );
}

function SecurityCard() {
  const t = useTranslations();
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting }
  } = useForm<{ password: string }>({ resolver: zodResolver(resetPasswordSchema) });
  const [success, setSuccess] = useState(false);

  async function onSubmit(values: { password: string }) {
    const supabase = createClient();
    const { error } = await supabase.auth.updateUser({ password: values.password });
    if (!error) {
      setSuccess(true);
      reset();
      setTimeout(() => setSuccess(false), 3000);
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("settings.security")}</CardTitle>
      </CardHeader>
      <form onSubmit={handleSubmit(onSubmit)} className="flex items-end gap-3">
        <div className="flex-1">
          <Label htmlFor="newPassword">{t("auth.resetPassword.password")}</Label>
          <Input id="newPassword" type="password" error={errors.password?.message} {...register("password")} />
          <FieldError>{errors.password?.message}</FieldError>
        </div>
        <Button type="submit" loading={isSubmitting}>
          {t("common.save")}
        </Button>
      </form>
      {success && <p className="mt-2 text-sm text-emerald-700">{t("auth.resetPassword.success")}</p>}
    </Card>
  );
}
