'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { CHAT_LANGUAGES, resolveLanguagePrefs } from '@/lib/domain/languages'
import { persistLanguagePrefs, useLocalLanguagePrefs } from '@/lib/domain/language-prefs-local'

const LANGUAGES = CHAT_LANGUAGES

const NOTIFICATIONS = [
  { key: 'invites', label: 'Trip invitations', desc: 'When someone invites you to a trip' },
  { key: 'warnings', label: 'Permit warnings', desc: 'Dimension mismatches, expirations, curfews, escorts' },
  { key: 'chat', label: 'Chat activity', desc: 'New messages and AI answers on your trips' },
  { key: 'status', label: 'Status changes', desc: 'When a trip goes active or completed' },
]

export function SettingsForm({
  userId,
  initialLanguages,
  initialPrimary,
}: {
  userId: string
  /** From the profile (Task 71); English only before the user adds any. */
  initialLanguages: string[]
  initialPrimary: string
}) {
  const [prefs, setPrefs] = useState<Record<string, boolean>>({
    invites: true,
    warnings: true,
    chat: false,
    status: true,
  })
  // Agent languages are REAL settings, saved to the profile (Task 71) — not a
  // preview like the notification toggles below.
  const serverLangs = resolveLanguagePrefs({ chat_languages: initialLanguages, primary_language: initialPrimary })
  const localLangs = useLocalLanguagePrefs(userId)
  const [savedLangs, setSavedLangs] = useState<typeof serverLangs | null>(null)
  const langs = savedLangs ?? localLangs ?? serverLangs
  const [savingLangs, setSavingLangs] = useState(false)

  async function saveLanguages(next: { languages: string[]; primary: string }) {
    setSavingLangs(true)
    try {
      // Reflected immediately; kept in this browser when the profile cannot
      // store it yet (same rule as the chat header).
      const { prefs } = await persistLanguagePrefs(userId, next)
      setSavedLangs(prefs)
      toast.success('Languages saved')
    } finally {
      setSavingLangs(false)
    }
  }

  function previewNote() {
    toast.info('Preview — preferences will save once account management is connected.')
  }

  return (
    <div className="mt-6 space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Email notifications</CardTitle>
          <CardDescription>What we email you about (delivery starts when the email service connects)</CardDescription>
        </CardHeader>
        <CardContent className="divide-y">
          {NOTIFICATIONS.map((n) => (
            <label key={n.key} className="flex cursor-pointer items-center justify-between gap-4 py-3">
              <span>
                <span className="block text-sm font-semibold">{n.label}</span>
                <span className="block text-xs text-neutral-500">{n.desc}</span>
              </span>
              <input
                type="checkbox"
                checked={prefs[n.key]}
                onChange={(e) => {
                  setPrefs((p) => ({ ...p, [n.key]: e.target.checked }))
                  previewNote()
                }}
                className="h-5 w-5 accent-[#0f1b2d]"
              />
            </label>
          ))}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Agent languages</CardTitle>
          <CardDescription>
            The languages you can switch the HeavyHaul Agent chat to, and the one every chat
            opens in. New accounts start with English only.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            {LANGUAGES.map((l) => {
              const enabled = langs.languages.includes(l.code)
              const isPrimary = langs.primary === l.code
              const lastOne = enabled && langs.languages.length === 1
              return (
                <div key={l.code} className="flex flex-wrap items-center gap-3 rounded-lg border px-3 py-2">
                  <label className="flex flex-1 cursor-pointer items-center gap-2 text-sm font-semibold">
                    <input
                      type="checkbox"
                      checked={enabled}
                      disabled={savingLangs || lastOne}
                      onChange={(e) => {
                        const languages = e.target.checked
                          ? [...langs.languages, l.code]
                          : langs.languages.filter((c) => c !== l.code)
                        const primary = languages.includes(langs.primary) ? langs.primary : languages[0]
                        saveLanguages({ languages, primary })
                      }}
                      className="h-4 w-4 accent-[#0f1b2d]"
                      title={lastOne ? 'Keep at least one language' : enabled ? 'Remove this language' : 'Add this language'}
                    />
                    {l.label}
                  </label>
                  {enabled && (
                    <label className="flex cursor-pointer items-center gap-1.5 text-xs text-neutral-600">
                      <input
                        type="radio"
                        name="settings-primary-language"
                        checked={isPrimary}
                        disabled={savingLangs}
                        onChange={() => saveLanguages({ languages: langs.languages, primary: l.code })}
                        className="accent-[#0f1b2d]"
                      />
                      Default
                    </label>
                  )}
                </div>
              )
            })}
          </div>
          <p className="mt-3 text-xs text-neutral-500">
            The official permit and provisions remain in their original language — translations are
            support, not legal authority.
          </p>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Password &amp; security</CardTitle>
        </CardHeader>
        <CardContent className="flex items-center justify-between">
          <p className="text-sm text-neutral-500">
            Passwords are managed by the administrator during the pilot.
          </p>
          <Button variant="outline" size="sm" onClick={previewNote}>
            Change password
          </Button>
        </CardContent>
      </Card>
    </div>
  )
}
