'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  useTwoFactorStatus,
  useSetup2FA,
  useVerify2FA,
  useDisable2FA,
  useRegenerateBackupCodes,
} from '@/hooks/use-two-factor'

export function TwoFactorSettings() {
  const { data: status, isLoading } = useTwoFactorStatus()
  const setup2FA = useSetup2FA()
  const verify2FA = useVerify2FA()
  const disable2FA = useDisable2FA()
  const regenerateBackupCodes = useRegenerateBackupCodes()

  // Setup dialog state
  const [showSetupDialog, setShowSetupDialog] = useState(false)
  const [setupData, setSetupData] = useState<{
    qrCode: string
    secret: string
  } | null>(null)
  const [verifyCode, setVerifyCode] = useState('')
  const [backupCodes, setBackupCodes] = useState<string[] | null>(null)

  // Disable dialog state
  const [showDisableDialog, setShowDisableDialog] = useState(false)
  const [disablePassword, setDisablePassword] = useState('')
  const [disableCode, setDisableCode] = useState('')

  // Regenerate backup codes dialog state
  const [showRegenerateDialog, setShowRegenerateDialog] = useState(false)
  const [regeneratePassword, setRegeneratePassword] = useState('')
  const [newBackupCodes, setNewBackupCodes] = useState<string[] | null>(null)

  const handleStartSetup = async () => {
    try {
      const data = await setup2FA.mutateAsync()
      setSetupData({ qrCode: data.qrCode, secret: data.secret })
      setShowSetupDialog(true)
    } catch {
      // Error handled by mutation
    }
  }

  const handleVerify = async () => {
    try {
      const result = await verify2FA.mutateAsync(verifyCode)
      setBackupCodes(result.backupCodes)
      setVerifyCode('')
    } catch {
      // Error handled by mutation
    }
  }

  const handleCloseSetupDialog = () => {
    setShowSetupDialog(false)
    setSetupData(null)
    setVerifyCode('')
    setBackupCodes(null)
  }

  const handleDisable = async () => {
    try {
      await disable2FA.mutateAsync({
        password: disablePassword,
        token: disableCode,
      })
      setShowDisableDialog(false)
      setDisablePassword('')
      setDisableCode('')
    } catch {
      // Error handled by mutation
    }
  }

  const handleRegenerateBackupCodes = async () => {
    try {
      const result = await regenerateBackupCodes.mutateAsync(regeneratePassword)
      setNewBackupCodes(result.backupCodes)
    } catch {
      // Error handled by mutation
    }
  }

  const handleCloseRegenerateDialog = () => {
    setShowRegenerateDialog(false)
    setRegeneratePassword('')
    setNewBackupCodes(null)
  }

  const copyBackupCodes = (codes: string[]) => {
    navigator.clipboard.writeText(codes.join('\n'))
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Two-Factor Authentication</CardTitle>
          <CardDescription>Loading...</CardDescription>
        </CardHeader>
      </Card>
    )
  }

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>Two-Factor Authentication</CardTitle>
          <CardDescription>
            Add an extra layer of security to your account by requiring a code
            from your authenticator app when you sign in.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {status?.enabled ? (
            <>
              <div className="flex items-center justify-between p-4 bg-green-50 rounded-lg">
                <div>
                  <p className="font-medium text-green-800">
                    Two-factor authentication is enabled
                  </p>
                  <p className="text-sm text-green-600">
                    Enabled on{' '}
                    {status.enabledAt
                      ? new Date(status.enabledAt).toLocaleDateString()
                      : 'Unknown date'}
                  </p>
                </div>
                <div className="text-green-600">
                  <svg
                    className="w-8 h-8"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"
                    />
                  </svg>
                </div>
              </div>

              <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                <div>
                  <p className="font-medium">Backup Codes</p>
                  <p className="text-sm text-gray-500">
                    {status.backupCodesRemaining} codes remaining
                  </p>
                </div>
                <Button
                  variant="outline"
                  onClick={() => setShowRegenerateDialog(true)}
                >
                  Regenerate
                </Button>
              </div>

              <Button
                variant="destructive"
                onClick={() => setShowDisableDialog(true)}
              >
                Disable Two-Factor Authentication
              </Button>
            </>
          ) : (
            <div className="flex items-center justify-between p-4 bg-yellow-50 rounded-lg">
              <div>
                <p className="font-medium text-yellow-800">
                  Two-factor authentication is not enabled
                </p>
                <p className="text-sm text-yellow-600">
                  We recommend enabling 2FA for added security
                </p>
              </div>
              <Button onClick={handleStartSetup} disabled={setup2FA.isPending}>
                {setup2FA.isPending ? 'Setting up...' : 'Enable 2FA'}
              </Button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Setup Dialog */}
      <Dialog open={showSetupDialog} onOpenChange={setShowSetupDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {backupCodes ? 'Save Your Backup Codes' : 'Set Up Two-Factor Authentication'}
            </DialogTitle>
            <DialogDescription>
              {backupCodes
                ? 'Save these backup codes in a safe place. You can use them to access your account if you lose your authenticator device.'
                : 'Scan the QR code with your authenticator app, then enter the code below.'}
            </DialogDescription>
          </DialogHeader>

          {backupCodes ? (
            <div className="space-y-4">
              <div className="p-4 bg-gray-100 rounded-lg font-mono text-sm">
                {backupCodes.map((code, i) => (
                  <div key={i} className="py-1">
                    {code}
                  </div>
                ))}
              </div>
              <Button
                variant="outline"
                className="w-full"
                onClick={() => copyBackupCodes(backupCodes)}
              >
                Copy All Codes
              </Button>
              <DialogFooter>
                <Button onClick={handleCloseSetupDialog}>
                  I have saved my codes
                </Button>
              </DialogFooter>
            </div>
          ) : (
            <div className="space-y-4">
              {setupData && (
                <>
                  <div className="flex justify-center">
                    <img
                      src={setupData.qrCode}
                      alt="2FA QR Code"
                      className="w-48 h-48"
                    />
                  </div>

                  <div className="text-center">
                    <p className="text-sm text-gray-500 mb-2">
                      Or enter this code manually:
                    </p>
                    <code className="px-2 py-1 bg-gray-100 rounded text-sm">
                      {setupData.secret}
                    </code>
                  </div>
                </>
              )}

              <div className="space-y-2">
                <Label htmlFor="verifyCode">Verification Code</Label>
                <Input
                  id="verifyCode"
                  type="text"
                  inputMode="numeric"
                  pattern="[0-9]*"
                  placeholder="123456"
                  value={verifyCode}
                  onChange={(e) => setVerifyCode(e.target.value)}
                  autoComplete="one-time-code"
                />
              </div>

              {verify2FA.error && (
                <p className="text-sm text-red-500">
                  {verify2FA.error.message}
                </p>
              )}

              <DialogFooter>
                <Button variant="outline" onClick={handleCloseSetupDialog}>
                  Cancel
                </Button>
                <Button
                  onClick={handleVerify}
                  disabled={!verifyCode || verify2FA.isPending}
                >
                  {verify2FA.isPending ? 'Verifying...' : 'Verify & Enable'}
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Disable Dialog */}
      <Dialog open={showDisableDialog} onOpenChange={setShowDisableDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Disable Two-Factor Authentication</DialogTitle>
            <DialogDescription>
              Enter your password and a verification code to disable 2FA.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="disablePassword">Password</Label>
              <Input
                id="disablePassword"
                type="password"
                value={disablePassword}
                onChange={(e) => setDisablePassword(e.target.value)}
                autoComplete="current-password"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="disableCode">
                Authentication Code or Backup Code
              </Label>
              <Input
                id="disableCode"
                type="text"
                placeholder="123456 or XXXX-XXXX"
                value={disableCode}
                onChange={(e) => setDisableCode(e.target.value)}
                autoComplete="one-time-code"
              />
            </div>

            {disable2FA.error && (
              <p className="text-sm text-red-500">
                {disable2FA.error.message}
              </p>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowDisableDialog(false)}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleDisable}
              disabled={!disablePassword || !disableCode || disable2FA.isPending}
            >
              {disable2FA.isPending ? 'Disabling...' : 'Disable 2FA'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Regenerate Backup Codes Dialog */}
      <Dialog
        open={showRegenerateDialog}
        onOpenChange={setShowRegenerateDialog}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>
              {newBackupCodes ? 'New Backup Codes' : 'Regenerate Backup Codes'}
            </DialogTitle>
            <DialogDescription>
              {newBackupCodes
                ? 'Save these new backup codes. Your old codes are now invalid.'
                : 'This will invalidate all existing backup codes.'}
            </DialogDescription>
          </DialogHeader>

          {newBackupCodes ? (
            <div className="space-y-4">
              <div className="p-4 bg-gray-100 rounded-lg font-mono text-sm">
                {newBackupCodes.map((code, i) => (
                  <div key={i} className="py-1">
                    {code}
                  </div>
                ))}
              </div>
              <Button
                variant="outline"
                className="w-full"
                onClick={() => copyBackupCodes(newBackupCodes)}
              >
                Copy All Codes
              </Button>
              <DialogFooter>
                <Button onClick={handleCloseRegenerateDialog}>
                  I have saved my codes
                </Button>
              </DialogFooter>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="regeneratePassword">
                  Enter your password to continue
                </Label>
                <Input
                  id="regeneratePassword"
                  type="password"
                  value={regeneratePassword}
                  onChange={(e) => setRegeneratePassword(e.target.value)}
                  autoComplete="current-password"
                />
              </div>

              {regenerateBackupCodes.error && (
                <p className="text-sm text-red-500">
                  {regenerateBackupCodes.error.message}
                </p>
              )}

              <DialogFooter>
                <Button
                  variant="outline"
                  onClick={handleCloseRegenerateDialog}
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleRegenerateBackupCodes}
                  disabled={!regeneratePassword || regenerateBackupCodes.isPending}
                >
                  {regenerateBackupCodes.isPending
                    ? 'Generating...'
                    : 'Generate New Codes'}
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  )
}
