'use client'

import { useState, useEffect } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useCreateOrder } from '@/hooks/use-orders'
import { useCustomers } from '@/hooks/use-customers'
import { SubscriptionTier } from '@/types/api'
import {
  Loader2,
  Search,
  User,
  Building2,
  Check,
  ChevronRight,
  ChevronLeft,
  Globe,
  Package,
  Layers,
  AlertCircle,
} from 'lucide-react'

interface CreateOrderDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess?: () => void
  preselectedCustomer?: {
    id: string
    name: string | null
    email: string
    company: string | null
  }
}

type Step = 'customer' | 'domain' | 'tier' | 'tools' | 'review'

// All available tools from the stacks folder
const ALL_TOOLS: Record<string, { name: string; description: string; category: string }> = {
  // Core Infrastructure
  orchestrator: { name: 'Orchestrator', description: 'LetsBe control plane API', category: 'Core' },
  sysadmin: { name: 'SysAdmin Agent', description: 'Remote automation worker', category: 'Core' },
  portainer: { name: 'Portainer', description: 'Container management UI', category: 'Core' },

  // Communication
  poste: { name: 'Poste.io', description: 'Email server with webmail', category: 'Communication' },
  chatwoot: { name: 'Chatwoot', description: 'Customer engagement platform', category: 'Communication' },
  listmonk: { name: 'Listmonk', description: 'Newsletter & mailing list manager', category: 'Communication' },

  // File Storage & Collaboration
  nextcloud: { name: 'Nextcloud', description: 'File sync & collaboration', category: 'Files' },
  minio: { name: 'MinIO', description: 'S3-compatible object storage', category: 'Files' },
  documenso: { name: 'Documenso', description: 'Document signing platform', category: 'Files' },

  // Identity & Security
  keycloak: { name: 'Keycloak', description: 'Identity & access management', category: 'Security' },
  vaultwarden: { name: 'Vaultwarden', description: 'Password manager (Bitwarden)', category: 'Security' },

  // Automation & Workflows
  n8n: { name: 'n8n', description: 'Workflow automation', category: 'Automation' },
  activepieces: { name: 'Activepieces', description: 'No-code automation platform', category: 'Automation' },
  windmill: { name: 'Windmill', description: 'Developer-first workflows', category: 'Automation' },
  typebot: { name: 'Typebot', description: 'Conversational app builder', category: 'Automation' },

  // Development
  gitea: { name: 'Gitea', description: 'Git server with web UI', category: 'Development' },
  'gitea-drone': { name: 'Drone CI', description: 'Continuous integration with Gitea', category: 'Development' },

  // Databases & Analytics
  nocodb: { name: 'NocoDB', description: 'Airtable alternative database UI', category: 'Data' },
  redash: { name: 'Redash', description: 'Data visualization & dashboards', category: 'Data' },
  umami: { name: 'Umami', description: 'Privacy-focused web analytics', category: 'Data' },

  // AI & Chat
  librechat: { name: 'LibreChat', description: 'ChatGPT-style AI interface', category: 'AI' },

  // CMS & Content
  ghost: { name: 'Ghost', description: 'Publishing platform & blog', category: 'Content' },
  wordpress: { name: 'WordPress', description: 'Content management system', category: 'Content' },
  squidex: { name: 'Squidex', description: 'Headless CMS', category: 'Content' },

  // Business Tools
  calcom: { name: 'Cal.com', description: 'Scheduling & calendar booking', category: 'Business' },
  odoo: { name: 'Odoo', description: 'ERP & business apps suite', category: 'Business' },
  penpot: { name: 'Penpot', description: 'Design & prototyping platform', category: 'Business' },

  // Monitoring & Maintenance
  glitchtip: { name: 'GlitchTip', description: 'Error tracking (Sentry alt)', category: 'Monitoring' },
  'uptime-kuma': { name: 'Uptime Kuma', description: 'Uptime monitoring', category: 'Monitoring' },
  'diun-watchtower': { name: 'Diun/Watchtower', description: 'Container update notifications', category: 'Monitoring' },

  // Other
  html: { name: 'Static HTML', description: 'Simple static website hosting', category: 'Other' },
}

// Default tools that are always included (core infrastructure)
const DEFAULT_TOOLS = ['html', 'portainer', 'diun-watchtower']

// Tool dependencies: selecting a tool automatically selects its dependencies
const TOOL_DEPENDENCIES: Record<string, string[]> = {
  'gitea': ['gitea-drone'],           // Gitea requires Drone CI
  'ghost': ['html'],                  // CMS tools require HTML
  'wordpress': ['html'],
  'squidex': ['html'],
}

// Tools that require HTML (website builders/CMS)
const WEBSITE_TOOLS = ['ghost', 'wordpress', 'squidex']

// Default tools by tier
const TOOLS_BY_TIER: Record<SubscriptionTier, string[]> = {
  HUB_DASHBOARD: [...DEFAULT_TOOLS, 'orchestrator', 'sysadmin', 'nextcloud', 'keycloak', 'minio', 'poste'],
  ADVANCED: Object.keys(ALL_TOOLS),
}

// Legacy compatibility
const TOOL_LABELS = ALL_TOOLS

export function CreateOrderDialog({
  open,
  onOpenChange,
  onSuccess,
  preselectedCustomer,
}: CreateOrderDialogProps) {
  const [step, setStep] = useState<Step>(preselectedCustomer ? 'domain' : 'customer')
  const [customerSearch, setCustomerSearch] = useState('')
  const [selectedCustomer, setSelectedCustomer] = useState<{
    id: string
    name: string | null
    email: string
    company: string | null
  } | null>(preselectedCustomer || null)
  const [domain, setDomain] = useState('')
  const [tier, setTier] = useState<SubscriptionTier>(SubscriptionTier.HUB_DASHBOARD)
  const [selectedTools, setSelectedTools] = useState<string[]>([])
  const [error, setError] = useState<string | null>(null)

  const { data: customersData, isLoading: isLoadingCustomers } = useCustomers({
    search: customerSearch || undefined,
    limit: 10,
  })

  const createOrder = useCreateOrder()

  // Initialize with preselected customer when dialog opens
  useEffect(() => {
    if (open && preselectedCustomer) {
      setSelectedCustomer(preselectedCustomer)
      setStep('domain')
    }
  }, [open, preselectedCustomer])

  // Reset state when dialog closes
  useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setStep(preselectedCustomer ? 'domain' : 'customer')
        setCustomerSearch('')
        setSelectedCustomer(preselectedCustomer || null)
        setDomain('')
        setTier(SubscriptionTier.HUB_DASHBOARD)
        setSelectedTools([])
        setError(null)
      }, 300)
    }
  }, [open, preselectedCustomer])

  // Auto-select default tools when tier changes
  useEffect(() => {
    setSelectedTools(TOOLS_BY_TIER[tier])
  }, [tier])

  const validateDomain = (domain: string): boolean => {
    const domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/
    return domainRegex.test(domain)
  }

  const handleNext = () => {
    setError(null)

    if (step === 'customer') {
      if (!selectedCustomer) {
        setError('Please select a customer')
        return
      }
      setStep('domain')
    } else if (step === 'domain') {
      if (!domain) {
        setError('Please enter a domain name')
        return
      }
      if (!validateDomain(domain)) {
        setError('Please enter a valid domain name')
        return
      }
      setStep('tier')
    } else if (step === 'tier') {
      setStep('tools')
    } else if (step === 'tools') {
      if (selectedTools.length === 0) {
        setError('Please select at least one tool')
        return
      }
      setStep('review')
    }
  }

  const handleBack = () => {
    setError(null)
    if (step === 'domain') setStep('customer')
    else if (step === 'tier') setStep('domain')
    else if (step === 'tools') setStep('tier')
    else if (step === 'review') setStep('tools')
  }

  const handleSubmit = async () => {
    if (!selectedCustomer) return

    try {
      await createOrder.mutateAsync({
        userId: selectedCustomer.id,
        domain,
        tier,
        tools: selectedTools,
      })
      onOpenChange(false)
      onSuccess?.()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create order')
    }
  }

  const toggleTool = (tool: string) => {
    setSelectedTools((prev) => {
      if (prev.includes(tool)) {
        // Removing a tool - also remove tools that depend on it
        let newTools = prev.filter((t) => t !== tool)
        // If removing gitea, also remove gitea-drone
        if (tool === 'gitea') {
          newTools = newTools.filter((t) => t !== 'gitea-drone')
        }
        return newTools
      } else {
        // Adding a tool - also add its dependencies
        const newTools = [...prev, tool]
        const deps = TOOL_DEPENDENCIES[tool]
        if (deps) {
          deps.forEach((dep) => {
            if (!newTools.includes(dep)) {
              newTools.push(dep)
            }
          })
        }
        return newTools
      }
    })
  }

  const steps: { key: Step; label: string; icon: React.ReactNode }[] = [
    { key: 'customer', label: 'Customer', icon: <User className="h-4 w-4" /> },
    { key: 'domain', label: 'Domain', icon: <Globe className="h-4 w-4" /> },
    { key: 'tier', label: 'Tier', icon: <Layers className="h-4 w-4" /> },
    { key: 'tools', label: 'Tools', icon: <Package className="h-4 w-4" /> },
    { key: 'review', label: 'Review', icon: <Check className="h-4 w-4" /> },
  ]

  const currentStepIndex = steps.findIndex((s) => s.key === step)

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Create New Order</DialogTitle>
          <DialogDescription>
            Create a new infrastructure order for a customer
          </DialogDescription>
        </DialogHeader>

        {/* Steps indicator */}
        <div className="flex items-center justify-between px-2 py-4">
          {steps.map((s, index) => (
            <div key={s.key} className="flex items-center">
              <div
                className={`flex items-center justify-center h-8 w-8 rounded-full border-2 transition-colors ${
                  index <= currentStepIndex
                    ? 'border-primary bg-primary text-white'
                    : 'border-gray-300 text-gray-400'
                }`}
              >
                {s.icon}
              </div>
              {index < steps.length - 1 && (
                <div
                  className={`w-12 h-0.5 mx-2 ${
                    index < currentStepIndex ? 'bg-primary' : 'bg-gray-300'
                  }`}
                />
              )}
            </div>
          ))}
        </div>

        {/* Step content */}
        <div className="min-h-[300px] py-4">
          {step === 'customer' && (
            <div className="space-y-4">
              <div>
                <Label>Search Customer</Label>
                <div className="relative mt-2">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    type="search"
                    placeholder="Search by name, email, or company..."
                    value={customerSearch}
                    onChange={(e) => setCustomerSearch(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>

              <div className="max-h-64 overflow-y-auto space-y-2">
                {isLoadingCustomers ? (
                  <div className="flex items-center justify-center py-8">
                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                  </div>
                ) : customersData?.customers && customersData.customers.length > 0 ? (
                  customersData.customers.map((customer) => (
                    <button
                      key={customer.id}
                      onClick={() => setSelectedCustomer(customer)}
                      className={`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${
                        selectedCustomer?.id === customer.id
                          ? 'border-primary bg-primary/5'
                          : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                      }`}
                    >
                      <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
                        <User className="h-5 w-5 text-primary" />
                      </div>
                      <div className="flex-1 text-left">
                        <p className="font-medium">{customer.name || customer.email}</p>
                        <div className="flex items-center gap-2 text-sm text-muted-foreground">
                          <span>{customer.email}</span>
                          {customer.company && (
                            <>
                              <span>-</span>
                              <span className="flex items-center gap-1">
                                <Building2 className="h-3 w-3" />
                                {customer.company}
                              </span>
                            </>
                          )}
                        </div>
                      </div>
                      {selectedCustomer?.id === customer.id && (
                        <Check className="h-5 w-5 text-primary" />
                      )}
                    </button>
                  ))
                ) : (
                  <div className="text-center py-8 text-muted-foreground">
                    {customerSearch ? 'No customers found' : 'Start typing to search customers'}
                  </div>
                )}
              </div>
            </div>
          )}

          {step === 'domain' && (
            <div className="space-y-4">
              <div>
                <Label htmlFor="domain">Domain Name</Label>
                <Input
                  id="domain"
                  type="text"
                  placeholder="example.com"
                  value={domain}
                  onChange={(e) => setDomain(e.target.value.toLowerCase())}
                  className="mt-2"
                />
                <p className="text-sm text-muted-foreground mt-2">
                  Enter the primary domain for this deployment. Services will be configured as subdomains.
                </p>
              </div>

              {selectedCustomer && (
                <div className="p-4 bg-gray-50 rounded-lg">
                  <p className="text-sm font-medium">Customer</p>
                  <p className="text-sm text-muted-foreground">
                    {selectedCustomer.name || selectedCustomer.email}
                    {selectedCustomer.company && ` - ${selectedCustomer.company}`}
                  </p>
                </div>
              )}
            </div>
          )}

          {step === 'tier' && (
            <div className="space-y-4">
              <Label>Select Tier</Label>
              <div className="grid gap-4">
                <button
                  onClick={() => setTier(SubscriptionTier.HUB_DASHBOARD)}
                  className={`p-4 rounded-lg border-2 text-left transition-colors ${
                    tier === SubscriptionTier.HUB_DASHBOARD
                      ? 'border-primary bg-primary/5'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-semibold">Hub Dashboard</p>
                      <p className="text-sm text-muted-foreground">
                        Essential tools: Nextcloud, Keycloak, MinIO, Poste
                      </p>
                    </div>
                    {tier === SubscriptionTier.HUB_DASHBOARD && (
                      <Check className="h-5 w-5 text-primary" />
                    )}
                  </div>
                </button>
                <button
                  onClick={() => setTier(SubscriptionTier.ADVANCED)}
                  className={`p-4 rounded-lg border-2 text-left transition-colors ${
                    tier === SubscriptionTier.ADVANCED
                      ? 'border-primary bg-primary/5'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="font-semibold">Advanced</p>
                      <p className="text-sm text-muted-foreground">
                        All tools including n8n, File Browser, Portainer, Grafana
                      </p>
                    </div>
                    {tier === SubscriptionTier.ADVANCED && (
                      <Check className="h-5 w-5 text-primary" />
                    )}
                  </div>
                </button>
              </div>
            </div>
          )}

          {step === 'tools' && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <Label>Select Tools</Label>
                  <p className="text-sm text-muted-foreground">
                    Choose which tools to deploy ({selectedTools.length} selected)
                  </p>
                </div>
                <div className="flex gap-2">
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setSelectedTools([])}
                  >
                    Clear All
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setSelectedTools(TOOLS_BY_TIER[tier])}
                  >
                    Defaults
                  </Button>
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={() => setSelectedTools(Object.keys(ALL_TOOLS))}
                  >
                    Select All
                  </Button>
                </div>
              </div>
              <div className="max-h-80 overflow-y-auto space-y-4 pr-2">
                {/* Group tools by category */}
                {Object.entries(
                  Object.entries(ALL_TOOLS).reduce((acc, [tool, info]) => {
                    if (!acc[info.category]) acc[info.category] = []
                    acc[info.category].push({ tool, ...info })
                    return acc
                  }, {} as Record<string, { tool: string; name: string; description: string; category: string }[]>)
                ).map(([category, tools]) => (
                  <div key={category}>
                    <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">{category}</p>
                    <div className="grid gap-1">
                      {tools.map(({ tool, name, description }) => {
                        const isSelected = selectedTools.includes(tool)
                        return (
                          <button
                            key={tool}
                            type="button"
                            onClick={() => toggleTool(tool)}
                            className={`flex items-center gap-3 p-2 rounded-lg border transition-colors ${
                              isSelected
                                ? 'border-primary bg-primary/5'
                                : 'border-gray-200 hover:border-gray-300'
                            }`}
                          >
                            <div
                              className={`h-4 w-4 rounded border-2 flex items-center justify-center flex-shrink-0 ${
                                isSelected ? 'border-primary bg-primary' : 'border-gray-300'
                              }`}
                            >
                              {isSelected && <Check className="h-2.5 w-2.5 text-white" />}
                            </div>
                            <div className="flex-1 text-left min-w-0">
                              <p className="font-medium text-sm">{name}</p>
                              <p className="text-xs text-muted-foreground truncate">{description}</p>
                            </div>
                          </button>
                        )
                      })}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 'review' && (
            <div className="space-y-4">
              <div className="bg-gray-50 rounded-lg p-4 space-y-4">
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Customer</p>
                  <p className="font-medium">
                    {selectedCustomer?.name || selectedCustomer?.email}
                    {selectedCustomer?.company && ` - ${selectedCustomer.company}`}
                  </p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Domain</p>
                  <p className="font-medium">{domain}</p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Tier</p>
                  <p className="font-medium capitalize">
                    {tier.replace('_', ' ').toLowerCase()}
                  </p>
                </div>
                <div>
                  <p className="text-sm font-medium text-muted-foreground">Tools ({selectedTools.length})</p>
                  <div className="flex flex-wrap gap-2 mt-1">
                    {selectedTools.map((tool) => (
                      <span
                        key={tool}
                        className="px-2 py-1 text-xs font-medium bg-primary/10 text-primary rounded"
                      >
                        {TOOL_LABELS[tool]?.name || tool}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Error message */}
        {error && (
          <div className="flex items-center gap-2 p-3 bg-red-50 border border-red-200 rounded-lg text-red-800">
            <AlertCircle className="h-4 w-4" />
            <span className="text-sm">{error}</span>
          </div>
        )}

        <DialogFooter className="mt-4">
          <div className="flex w-full justify-between">
            <Button
              variant="outline"
              onClick={handleBack}
              disabled={step === 'customer' || (step === 'domain' && !!preselectedCustomer) || createOrder.isPending}
            >
              <ChevronLeft className="h-4 w-4 mr-2" />
              Back
            </Button>
            {step === 'review' ? (
              <Button onClick={handleSubmit} disabled={createOrder.isPending}>
                {createOrder.isPending ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Creating...
                  </>
                ) : (
                  <>
                    Create Order
                    <Check className="h-4 w-4 ml-2" />
                  </>
                )}
              </Button>
            ) : (
              <Button onClick={handleNext}>
                Next
                <ChevronRight className="h-4 w-4 ml-2" />
              </Button>
            )}
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
