import { useState, type ReactNode } from 'react'
import { Eye, EyeOff, Trash2, Undo2, type LucideIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { dateFormat } from '@/components/admin/AdminUi'
import { cn } from '@/lib/utils'

// Building blocks for the provider settings page (/admin/settings).

export type SettingMeta = { key: string; label: string; secret: boolean; hint: string }

export type SettingFieldState = {
  key: string
  source: 'dashboard' | 'env' | 'none'
  value: string
  preview: string | null
  updatedBy: string | null
  updatedAt: string | null
}

const SOURCE_LABEL = {
  dashboard: { text: 'Saved here', className: 'bg-primary/10 text-primary ring-primary/20' },
  env: { text: 'From environment variable', className: 'bg-secondary text-muted-foreground ring-border' },
  none: { text: 'Not set', className: 'bg-[var(--gold-glow)]/20 text-[oklch(0.45_0.1_70)] ring-[var(--gold-glow)]/40' },
} as const

export function Section({
  icon: Icon,
  title,
  description,
  children,
}: {
  icon: LucideIcon
  title: string
  description: string
  children: ReactNode
}) {
  return (
    <section className="mt-6 grid gap-5 rounded-[1.5rem] border bg-card p-6 shadow-deep md:grid-cols-[14rem_1fr]">
      <div className="grid content-start gap-1">
        <h2 className="flex items-center gap-2 text-lg font-bold">
          <Icon className="size-4 text-primary" aria-hidden /> {title}
        </h2>
        <p className="text-sm text-muted-foreground">{description}</p>
      </div>
      <div className="grid gap-5">{children}</div>
    </section>
  )
}

export function ReadyCard({
  icon: Icon,
  title,
  ready,
  children,
}: {
  icon: LucideIcon
  title: string
  ready: boolean
  children: ReactNode
}) {
  return (
    <div className="flex items-center gap-3 rounded-2xl border bg-card p-4 shadow-deep">
      <span
        className={cn(
          'grid size-10 place-items-center rounded-xl',
          ready ? 'bg-primary/10 text-primary' : 'bg-[var(--gold-glow)]/20 text-[oklch(0.45_0.1_70)]',
        )}
      >
        <Icon className="size-5" aria-hidden />
      </span>
      <div className="min-w-0">
        <p className="font-semibold">
          {title} · {ready ? 'Ready' : 'Not configured'}
        </p>
        <p className="text-sm text-muted-foreground">{children}</p>
      </div>
    </div>
  )
}

export function SettingField({
  meta,
  idPrefix,
  field,
  value,
  onChange,
  cleared,
  onToggleClear,
  disabled,
}: {
  meta: SettingMeta
  idPrefix: string
  field: SettingFieldState
  value: string
  onChange: (value: string) => void
  cleared: boolean
  onToggleClear: () => void
  disabled: boolean
}) {
  const [reveal, setReveal] = useState(false)
  const id = `${idPrefix}-${field.key}`
  const source = SOURCE_LABEL[field.source]
  const placeholder = meta.secret
    ? field.source === 'dashboard'
      ? `Saved (${field.preview}). Leave blank to keep it`
      : field.source === 'env'
        ? 'Leave blank to use the environment variable'
        : 'Paste the key'
    : field.source === 'env'
      ? 'Leave blank to use the environment variable'
      : undefined

  return (
    <div className="grid gap-2">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <Label htmlFor={id}>{meta.label}</Label>
        <span className={cn('rounded-full px-2 py-0.5 text-[0.7rem] font-medium ring-1 ring-inset', source.className)}>
          {cleared ? 'Will be removed' : source.text}
        </span>
      </div>
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Input
            id={id}
            type={meta.secret && !reveal ? 'password' : field.key === 'businessEmail' ? 'email' : 'text'}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder={placeholder}
            autoComplete="off"
            spellCheck={false}
            maxLength={500}
            disabled={disabled || cleared}
            className={cn('font-mono', meta.secret && 'pr-10')}
          />
          {meta.secret && (
            <button
              type="button"
              onClick={() => setReveal((r) => !r)}
              className="absolute inset-y-0 right-0 grid w-10 place-items-center text-muted-foreground hover:text-foreground"
              aria-label={reveal ? `Hide ${meta.label}` : `Show ${meta.label}`}
            >
              {reveal ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
            </button>
          )}
        </div>
        {field.source === 'dashboard' && (
          <Button type="button" variant="outline" size="icon" onClick={onToggleClear} disabled={disabled} title={cleared ? 'Keep this value' : 'Remove the saved value'}>
            {cleared ? <Undo2 /> : <Trash2 />}
            <span className="sr-only">{cleared ? `Keep ${meta.label}` : `Remove ${meta.label}`}</span>
          </Button>
        )}
      </div>
      <p className="text-xs text-muted-foreground">
        {meta.hint}
        {field.updatedAt && !cleared && (
          <> · Updated by {field.updatedBy} on {dateFormat.format(new Date(field.updatedAt))}</>
        )}
      </p>
    </div>
  )
}
