"use client"

import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { useMailAccounts } from "@/lib/api/hooks/use-mail-queries"
import type { ApiTokenMailScope } from "@/lib/api/types"
import { AutomationBorderedFieldset } from "@/components/gmail/settings/automation/automation-bordered-fieldset"

export function ApiTokenMailScopeEditor({
  scope,
  onChange,
  enabled,
  className,
}: {
  scope: ApiTokenMailScope
  onChange: (scope: ApiTokenMailScope) => void
  enabled: boolean
  className?: string
}) {
  const { data: accounts = [], isLoading } = useMailAccounts()

  if (!enabled) return null

  function toggleAccount(accountId: string) {
    const ids = scope.account_ids.includes(accountId)
      ? scope.account_ids.filter((id) => id !== accountId)
      : [...scope.account_ids, accountId]
    onChange({ all_accounts: false, account_ids: ids })
  }

  return (
    <AutomationBorderedFieldset
      className={className}
      legend="Périmètre mail — comptes"
    >
      <label className="flex items-start gap-2">
        <Checkbox
          checked={scope.all_accounts}
          onCheckedChange={(checked) =>
            onChange({
              all_accounts: checked === true,
              account_ids: checked === true ? [] : scope.account_ids,
            })
          }
          className="mt-0.5"
        />
        <span className="text-sm">
          Tous les comptes mail
          <span className="mt-0.5 block text-xs text-muted-foreground">
            Le token pourra accéder à l&apos;ensemble des boîtes rattachées.
          </span>
        </span>
      </label>

      {!scope.all_accounts && (
        <div className="space-y-2 pl-1">
          <Label className="text-xs text-muted-foreground">Comptes autorisés</Label>
          {isLoading ? (
            <p className="text-sm text-muted-foreground">Chargement des comptes…</p>
          ) : accounts.length === 0 ? (
            <p className="text-sm text-muted-foreground">Aucun compte mail configuré.</p>
          ) : (
            <ul className="space-y-1.5">
              {accounts.map((account) => (
                <li key={account.id}>
                  <label className="flex cursor-pointer items-center gap-2 rounded-md border border-border px-2.5 py-2 hover:bg-muted/40">
                    <Checkbox
                      checked={scope.account_ids.includes(account.id)}
                      onCheckedChange={() => toggleAccount(account.id)}
                    />
                    <span className="min-w-0 text-sm">
                      <span className="block truncate font-medium">
                        {account.name || account.email}
                      </span>
                      <span className="block truncate text-xs text-muted-foreground">
                        {account.email}
                      </span>
                    </span>
                  </label>
                </li>
              ))}
            </ul>
          )}
        </div>
      )}
    </AutomationBorderedFieldset>
  )
}
