'use client'

import { useState } from 'react'
import { ExternalLink, Copy, Check, Eye, EyeOff, Edit2, Loader2, AlertCircle } from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import {
  usePortainerCredentials,
  useUpdatePortainerCredentials,
  useTestPortainerConnection,
} from '@/hooks/use-portainer'

function formatRelativeTime(date: Date): string {
  const now = Date.now()
  const diff = now - date.getTime()
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (days > 0) return `${days} day${days > 1 ? 's' : ''} ago`
  if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''} ago`
  if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`
  return 'just now'
}

interface PortainerCredentialsPanelProps {
  orderId: string
  /** If true, poll every 5 seconds until credentials are configured (useful after provisioning) */
  pollUntilConfigured?: boolean
}

export function PortainerCredentialsPanel({ orderId, pollUntilConfigured = true }: PortainerCredentialsPanelProps) {
  const { data: credentials, isLoading, error } = usePortainerCredentials(orderId, pollUntilConfigured)
  const updateCredentials = useUpdatePortainerCredentials()
  const testConnection = useTestPortainerConnection()

  const [isEditing, setIsEditing] = useState(false)
  const [showPassword, setShowPassword] = useState(false)
  const [copiedField, setCopiedField] = useState<string | null>(null)
  const [editForm, setEditForm] = useState({ username: '', password: '' })

  const copyToClipboard = async (text: string, field: string) => {
    await navigator.clipboard.writeText(text)
    setCopiedField(field)
    setTimeout(() => setCopiedField(null), 2000)
  }

  const handleStartEdit = () => {
    setEditForm({
      username: credentials?.username || '',
      password: credentials?.password || '',
    })
    setIsEditing(true)
  }

  const handleSaveCredentials = async () => {
    try {
      await updateCredentials.mutateAsync({
        orderId,
        username: editForm.username,
        password: editForm.password,
      })
      setIsEditing(false)
    } catch (error) {
      console.error('Failed to save credentials:', error)
    }
  }

  const handleTestConnection = async () => {
    await testConnection.mutateAsync(orderId)
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <div className="w-3 h-3 bg-blue-500 rounded-full" />
            Portainer
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-4">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <div className="w-3 h-3 bg-blue-500 rounded-full" />
            Portainer
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2 text-destructive">
            <AlertCircle className="h-4 w-4" />
            <span>Failed to load credentials</span>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <div className="w-3 h-3 bg-blue-500 rounded-full" />
              Portainer
            </CardTitle>
            <CardDescription>Container management credentials</CardDescription>
          </div>
          <div className="flex items-center gap-2">
            {credentials?.isConfigured ? (
              <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                Configured
              </Badge>
            ) : (
              <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-200">
                Not Configured
              </Badge>
            )}
            {!isEditing && (
              <Button variant="ghost" size="sm" onClick={handleStartEdit}>
                <Edit2 className="h-4 w-4" />
              </Button>
            )}
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-4">
        {isEditing ? (
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="edit-username">Username</Label>
              <Input
                id="edit-username"
                value={editForm.username}
                onChange={(e) => setEditForm((prev) => ({ ...prev, username: e.target.value }))}
                placeholder="admin-xxxxxxxx"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-password">Password</Label>
              <Input
                id="edit-password"
                type="password"
                value={editForm.password}
                onChange={(e) => setEditForm((prev) => ({ ...prev, password: e.target.value }))}
                placeholder="Enter password"
              />
            </div>
            <div className="flex gap-2">
              <Button onClick={handleSaveCredentials} disabled={updateCredentials.isPending}>
                {updateCredentials.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Save
              </Button>
              <Button variant="outline" onClick={() => setIsEditing(false)}>
                Cancel
              </Button>
            </div>
          </div>
        ) : (
          <>
            {/* URL */}
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">Portainer URL</Label>
              <div className="flex items-center gap-2">
                {credentials?.url ? (
                  <>
                    <a
                      href={credentials.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-sm text-blue-600 hover:underline flex items-center gap-1"
                    >
                      {credentials.url}
                      <ExternalLink className="h-3 w-3" />
                    </a>
                  </>
                ) : (
                  <span className="text-sm text-muted-foreground">Not available</span>
                )}
              </div>
            </div>

            {/* Username */}
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">Username</Label>
              <div className="flex items-center gap-2">
                <code className="text-sm bg-muted px-2 py-1 rounded">
                  {credentials?.username || '-'}
                </code>
                {credentials?.username && (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-7 w-7 p-0"
                    onClick={() => copyToClipboard(credentials.username!, 'username')}
                  >
                    {copiedField === 'username' ? (
                      <Check className="h-3 w-3 text-green-600" />
                    ) : (
                      <Copy className="h-3 w-3" />
                    )}
                  </Button>
                )}
              </div>
            </div>

            {/* Password */}
            <div className="space-y-1">
              <Label className="text-xs text-muted-foreground">Password</Label>
              <div className="flex items-center gap-2">
                <code className="text-sm bg-muted px-2 py-1 rounded font-mono">
                  {credentials?.password
                    ? showPassword
                      ? credentials.password
                      : '••••••••••••••••'
                    : '-'}
                </code>
                {credentials?.password && (
                  <>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 w-7 p-0"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 w-7 p-0"
                      onClick={() => copyToClipboard(credentials.password!, 'password')}
                    >
                      {copiedField === 'password' ? (
                        <Check className="h-3 w-3 text-green-600" />
                      ) : (
                        <Copy className="h-3 w-3" />
                      )}
                    </Button>
                  </>
                )}
              </div>
            </div>

            {/* Sync status */}
            {credentials?.syncedAt && (
              <div className="text-xs text-muted-foreground">
                Last synced: {formatRelativeTime(new Date(credentials.syncedAt))}
              </div>
            )}

            {/* Test connection button */}
            {credentials?.isConfigured && (
              <div className="pt-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleTestConnection}
                  disabled={testConnection.isPending}
                >
                  {testConnection.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Test Connection
                </Button>
                {testConnection.data && (
                  <span
                    className={`ml-2 text-sm ${
                      testConnection.data.success ? 'text-green-600' : 'text-red-600'
                    }`}
                  >
                    {testConnection.data.success
                      ? 'Connection successful'
                      : testConnection.data.error || 'Connection failed'}
                  </span>
                )}
              </div>
            )}
          </>
        )}
      </CardContent>
    </Card>
  )
}
