'use client'

import { useState, useEffect } from '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 {
  Loader2,
  Pencil,
  X,
  Check,
  Settings2,
  RefreshCw,
  Copy,
  CheckCircle,
} from 'lucide-react'
import type { Order, UserSummary } from '@/types/api'

interface ProvisioningConfigFormProps {
  order: Order
  onSave: (config: ProvisioningConfig) => Promise<void>
  isEditable: boolean
  isSaving?: boolean
}

export interface ProvisioningConfig {
  customer: string
  companyName: string
  licenseKey: string
}

// Client-side slugify function - only lowercase letters (env_setup.sh requires ^[a-z]+$)
function slugifyCustomer(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z]/g, '')  // Only keep lowercase letters
    .substring(0, 32)
}

// Client-side license key generator (for display purposes)
function generateClientLicenseKey(): string {
  const array = new Uint8Array(16)
  crypto.getRandomValues(array)
  const hex = Array.from(array)
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('')
  return `lb_inst_${hex}`
}

export function ProvisioningConfigForm({
  order,
  onSave,
  isEditable,
  isSaving = false,
}: ProvisioningConfigFormProps) {
  const [isEditing, setIsEditing] = useState(false)
  const [saving, setSaving] = useState(false)
  const [copiedField, setCopiedField] = useState<string | null>(null)

  // Form state
  const [customer, setCustomer] = useState(order.customer || '')
  const [companyName, setCompanyName] = useState(order.companyName || '')
  const [licenseKey, setLicenseKey] = useState(order.licenseKey || '')

  // Auto-populate defaults when entering edit mode if fields are empty
  useEffect(() => {
    if (isEditing) {
      const userCompany = order.user.company || order.user.name || ''

      if (!customer && userCompany) {
        setCustomer(slugifyCustomer(userCompany))
      }
      if (!companyName && userCompany) {
        setCompanyName(userCompany)
      }
      if (!licenseKey) {
        setLicenseKey(generateClientLicenseKey())
      }
    }
  }, [isEditing, order.user.company, order.user.name])

  const handleRegenerateLicenseKey = () => {
    setLicenseKey(generateClientLicenseKey())
  }

  const handleSave = async () => {
    if (!customer.trim() || !companyName.trim() || !licenseKey.trim()) {
      return
    }

    setSaving(true)
    try {
      await onSave({
        customer: customer.trim(),
        companyName: companyName.trim(),
        licenseKey: licenseKey.trim(),
      })
      setIsEditing(false)
    } catch (error) {
      console.error('Failed to save provisioning config:', error)
    } finally {
      setSaving(false)
    }
  }

  const handleCancel = () => {
    setCustomer(order.customer || '')
    setCompanyName(order.companyName || '')
    setLicenseKey(order.licenseKey || '')
    setIsEditing(false)
  }

  const copyToClipboard = async (value: string, field: string) => {
    try {
      await navigator.clipboard.writeText(value)
      setCopiedField(field)
      setTimeout(() => setCopiedField(null), 2000)
    } catch {
      console.error('Failed to copy to clipboard')
    }
  }

  const hasConfig = order.customer && order.companyName && order.licenseKey

  // Display mode
  if (!isEditing) {
    return (
      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Settings2 className="h-5 w-5" />
              Provisioning Config
            </CardTitle>
            <CardDescription>
              Customer and license information for provisioning
            </CardDescription>
          </div>
          {isEditable && (
            <Button variant="outline" size="sm" onClick={() => setIsEditing(true)}>
              <Pencil className="mr-2 h-4 w-4" />
              {hasConfig ? 'Edit Config' : 'Configure'}
            </Button>
          )}
        </CardHeader>
        <CardContent>
          {!hasConfig ? (
            <p className="text-muted-foreground text-sm">
              No provisioning config set. Click &quot;Configure&quot; to set up customer details and generate a license key.
            </p>
          ) : (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground text-xs">Customer ID</Label>
                  <div className="flex items-center gap-2">
                    <code className="bg-muted px-2 py-1 rounded text-sm font-mono">
                      {order.customer}
                    </code>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 w-7 p-0"
                      onClick={() => copyToClipboard(order.customer!, 'customer')}
                    >
                      {copiedField === 'customer' ? (
                        <CheckCircle className="h-3.5 w-3.5 text-green-500" />
                      ) : (
                        <Copy className="h-3.5 w-3.5" />
                      )}
                    </Button>
                  </div>
                </div>
                <div>
                  <Label className="text-muted-foreground text-xs">Company Name</Label>
                  <p className="text-sm font-medium">{order.companyName}</p>
                </div>
              </div>
              <div>
                <Label className="text-muted-foreground text-xs">License Key</Label>
                <div className="flex items-center gap-2">
                  <code className="bg-muted px-2 py-1 rounded text-sm font-mono break-all">
                    {order.licenseKey}
                  </code>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-7 w-7 p-0"
                    onClick={() => copyToClipboard(order.licenseKey!, 'licenseKey')}
                  >
                    {copiedField === 'licenseKey' ? (
                      <CheckCircle className="h-3.5 w-3.5 text-green-500" />
                    ) : (
                      <Copy className="h-3.5 w-3.5" />
                    )}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    )
  }

  // Edit mode
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
        <div>
          <CardTitle className="flex items-center gap-2">
            <Settings2 className="h-5 w-5" />
            Edit Provisioning Config
          </CardTitle>
          <CardDescription>
            Configure customer details and license key for this order
          </CardDescription>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleCancel} disabled={saving}>
            <X className="mr-2 h-4 w-4" />
            Cancel
          </Button>
          <Button
            size="sm"
            onClick={handleSave}
            disabled={saving || !customer.trim() || !companyName.trim() || !licenseKey.trim()}
          >
            {saving ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Check className="mr-2 h-4 w-4" />
                Save Config
              </>
            )}
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="customer">Customer ID</Label>
              <Input
                id="customer"
                value={customer}
                onChange={(e) => setCustomer(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                placeholder="acme-corp"
                className="font-mono"
                maxLength={32}
              />
              <p className="text-xs text-muted-foreground">
                Used for container names (e.g., {customer || 'acme'}-portainer, {customer || 'acme'}-nextcloud)
              </p>
            </div>
            <div className="space-y-2">
              <Label htmlFor="companyName">Company Name</Label>
              <Input
                id="companyName"
                value={companyName}
                onChange={(e) => setCompanyName(e.target.value)}
                placeholder="Acme Corporation"
              />
              <p className="text-xs text-muted-foreground">
                Display name shown in the dashboard
              </p>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="licenseKey">License Key</Label>
            <div className="flex gap-2">
              <Input
                id="licenseKey"
                value={licenseKey}
                onChange={(e) => setLicenseKey(e.target.value)}
                placeholder="lb_inst_..."
                className="font-mono flex-1"
                readOnly
              />
              <Button
                type="button"
                variant="outline"
                size="icon"
                onClick={handleRegenerateLicenseKey}
                title="Regenerate license key"
              >
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">
              Auto-generated unique identifier for this instance
            </p>
          </div>

          <div className="rounded-lg bg-blue-50 p-3 text-sm text-blue-800">
            <strong>Note:</strong> These values will be used during provisioning to configure
            the server. The customer ID is used for Docker container names, and the license key
            identifies this instance in phone-home communications.
          </div>
        </div>
      </CardContent>
    </Card>
  )
}
