import { GitBranch } from '@phosphor-icons/react'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import type { AppLocale } from '../lib/i18n'

function gitSetupCopy(locale: AppLocale) {
  if (locale === 'zh-CN') return {
    title: '为当前知识库启用版本记录？',
    description: '不启用 Git 也可以继续使用这个知识库。启用前，历史记录、同步、提交和变更查看功能暂不可用。',
    never: '此知识库永不提示',
    later: '暂不启用',
    enable: '启用 Git',
    enabling: '正在启用…',
  }
  return {
    title: 'Enable version history for this workspace?',
    description: 'You can keep using this workspace without Git. History, sync, commits, and change views remain unavailable until Git is enabled.',
    never: 'Never for this workspace',
    later: 'Not now',
    enable: 'Enable Git',
    enabling: 'Enabling…',
  }
}

interface GitSetupDialogProps {
  open: boolean
  onInitGit: () => Promise<void>
  onDismiss: () => void
  onNeverForVault?: () => void
  locale?: AppLocale
}

export function GitSetupDialog({ open, onInitGit, onDismiss, onNeverForVault, locale = 'en' }: GitSetupDialogProps) {
  const copy = gitSetupCopy(locale)
  const [creating, setCreating] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleCreate = async () => {
    setCreating(true)
    setError(null)
    try {
      await onInitGit()
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err))
      setCreating(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(nextOpen) => {
      if (!nextOpen && !creating) onDismiss()
    }}>
      <DialogContent className="sm:max-w-lg gap-5 p-7">
        <DialogHeader>
          <div className="mb-1 flex size-9 items-center justify-center rounded-md bg-muted text-muted-foreground">
            <GitBranch size={18} />
          </div>
          <DialogTitle className="text-[22px] leading-8">{copy.title}</DialogTitle>
          <DialogDescription className="text-[16px] leading-7">
            {copy.description}
          </DialogDescription>
        </DialogHeader>
        {error && (
          <p className="m-0 rounded-md bg-destructive/10 px-3 py-2 text-[12px] text-destructive">
            {error}
          </p>
        )}
        <DialogFooter>
          <Button className="h-11 px-4 text-[15px]" variant="ghost" onClick={onNeverForVault} disabled={creating}>
            {copy.never}
          </Button>
          <Button className="h-11 px-4 text-[15px]" variant="outline" onClick={onDismiss} disabled={creating}>
            {copy.later}
          </Button>
          <Button className="h-11 px-4 text-[15px]" onClick={handleCreate} disabled={creating}>
            {creating ? copy.enabling : copy.enable}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
