import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { 
  Loader2, 
  Server, 
  Database,
  Code2,
  Globe,
  ShoppingCart,
  Zap,
  UserPlus,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  RefreshCw,
  Copy,
  Download,
  Check,
} from "lucide-react"
import { useSystemInfo } from "../hooks/use-system-info"
import { 
  minimumRequirements, 
  requiredExtensions, 
  recommendedExtensions,
  compareVersions,
  compareMemory,
  SystemRequirement
} from "../config"

function StatusIcon({ status }: { status: 'pass' | 'warning' | 'fail' }) {
  switch (status) {
    case 'pass':
      return <CheckCircle2 className="h-4 w-4 text-green-600" />
    case 'warning':
      return <AlertTriangle className="h-4 w-4 text-yellow-600" />
    case 'fail':
      return <XCircle className="h-4 w-4 text-red-600" />
  }
}

function StatusBadge({ status }: { status: 'pass' | 'warning' | 'fail' }) {
  const variants = {
    pass: 'bg-green-100 text-green-800 border-green-200',
    warning: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    fail: 'bg-red-100 text-red-800 border-red-200',
  }
  
  const labels = {
    pass: 'OK',
    warning: 'Warning',
    fail: 'Failed',
  }
  
  return (
    <Badge variant="outline" className={variants[status]}>
      {labels[status]}
    </Badge>
  )
}

function RequirementRow({ req }: { req: SystemRequirement }) {
  return (
    <div className="flex items-center justify-between py-3 px-4 rounded-lg border">
      <div className="flex items-center gap-3">
        <StatusIcon status={req.status} />
        <div>
          <p className="font-medium">{req.name}</p>
          {req.description && (
            <p className="text-sm text-muted-foreground">{req.description}</p>
          )}
        </div>
      </div>
      <div className="flex items-center gap-4">
        <div className="text-right">
          <p className="text-sm">
            <span className="text-muted-foreground">Required: </span>
            <span className="font-medium">{req.required}</span>
          </p>
          <p className="text-sm">
            <span className="text-muted-foreground">Current: </span>
            <span className={`font-medium ${
              req.status === 'pass' ? 'text-green-600' : 
              req.status === 'warning' ? 'text-yellow-600' : 'text-red-600'
            }`}>
              {req.current}
            </span>
          </p>
        </div>
        <StatusBadge status={req.status} />
      </div>
    </div>
  )
}

function InfoRow({ label, value, mono = false }: { label: string; value: string | number | boolean; mono?: boolean }) {
  const displayValue = typeof value === 'boolean' ? (value ? 'Yes' : 'No') : String(value)
  
  return (
    <div className="flex items-center justify-between py-2.5 px-4 rounded-lg hover:bg-muted/50">
      <span className="text-muted-foreground">{label}</span>
      <span className={`font-medium ${mono ? 'font-mono text-sm' : ''}`}>{displayValue || 'N/A'}</span>
    </div>
  )
}

export function SystemInfoPage() {
  const { 
    systemInfo, 
    loading, 
    error, 
    copying, 
    refresh, 
    copyToClipboard, 
    downloadReport 
  } = useSystemInfo()

  if (loading) {
    return (
      <div className="flex flex-1 items-center justify-center p-6">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto text-primary" />
          <p className="mt-4 text-sm text-muted-foreground">Loading system information...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex flex-1 flex-col items-center justify-center p-6 gap-4">
        <XCircle className="h-12 w-12 text-red-500" />
        <p className="text-lg font-medium">Failed to load system info</p>
        <p className="text-sm text-muted-foreground">{error}</p>
        <Button onClick={refresh}>
          <RefreshCw className="h-4 w-4 mr-2" />
          Retry
        </Button>
      </div>
    )
  }

  // Build requirements list
  const requirements: SystemRequirement[] = [
    {
      name: 'PHP Version',
      required: minimumRequirements.php.version + '+',
      current: systemInfo.php.version,
      status: compareVersions(systemInfo.php.version, minimumRequirements.php.version),
    },
    {
      name: 'PHP Memory Limit',
      required: minimumRequirements.php.memoryLimit,
      current: systemInfo.php.memoryLimit,
      status: compareMemory(systemInfo.php.memoryLimit, minimumRequirements.php.memoryLimit),
    },
    {
      name: 'WordPress Version',
      required: minimumRequirements.wordpress.version + '+',
      current: systemInfo.wordpress.version,
      status: compareVersions(systemInfo.wordpress.version, minimumRequirements.wordpress.version),
    },
    {
      name: 'WordPress Memory Limit',
      required: minimumRequirements.wordpress.memoryLimit,
      current: systemInfo.wordpress.memoryLimit,
      status: compareMemory(systemInfo.wordpress.memoryLimit, minimumRequirements.wordpress.memoryLimit),
    },
    {
      name: 'MySQL Version',
      required: minimumRequirements.mysql.version + '+',
      current: systemInfo.mysql.version,
      status: compareVersions(systemInfo.mysql.version, minimumRequirements.mysql.version),
    },
    {
      name: 'WooCommerce Version',
      required: minimumRequirements.woocommerce.version + '+',
      current: systemInfo.woocommerce.version || 'Not Installed',
      status: systemInfo.woocommerce.version 
        ? compareVersions(systemInfo.woocommerce.version, minimumRequirements.woocommerce.version)
        : 'fail',
    },
  ]

  const passCount = requirements.filter(r => r.status === 'pass').length
  const warningCount = requirements.filter(r => r.status === 'warning').length
  const failCount = requirements.filter(r => r.status === 'fail').length

  // Check PHP extensions
  const extensionStatus = requiredExtensions.map(ext => ({
    name: ext,
    installed: systemInfo.php.extensions.includes(ext),
    required: true,
  }))

  const recommendedStatus = recommendedExtensions.map(ext => ({
    name: ext,
    installed: systemInfo.php.extensions.includes(ext),
    required: false,
  }))

  return (
    <div className="flex flex-1 flex-col gap-6 p-6 overflow-auto">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div className="flex items-center gap-3">
          <div className="flex h-12 w-12 items-center justify-center rounded-lg text-white" style={{ backgroundColor: '#00226b' }}>
            <Server className="h-6 w-6" />
          </div>
          <div>
            <h1 className="text-2xl font-bold tracking-tight">System Info</h1>
            <p className="text-sm text-muted-foreground">
              Server configuration and requirements status
            </p>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={refresh}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </Button>
          <Button variant="outline" size="sm" onClick={copyToClipboard}>
            {copying ? (
              <>
                <Check className="h-4 w-4 mr-2" />
                Copied!
              </>
            ) : (
              <>
                <Copy className="h-4 w-4 mr-2" />
                Copy
              </>
            )}
          </Button>
          <Button variant="outline" size="sm" onClick={downloadReport}>
            <Download className="h-4 w-4 mr-2" />
            Download
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid gap-4 md:grid-cols-3">
        <Card className={passCount === requirements.length ? 'border-green-200 bg-green-50' : ''}>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
              <CheckCircle2 className="h-6 w-6 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-green-600">{passCount}</p>
              <p className="text-sm text-muted-foreground">Requirements Passed</p>
            </div>
          </CardContent>
        </Card>
        <Card className={warningCount > 0 ? 'border-yellow-200 bg-yellow-50' : ''}>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-yellow-100">
              <AlertTriangle className="h-6 w-6 text-yellow-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-yellow-600">{warningCount}</p>
              <p className="text-sm text-muted-foreground">Warnings</p>
            </div>
          </CardContent>
        </Card>
        <Card className={failCount > 0 ? 'border-red-200 bg-red-50' : ''}>
          <CardContent className="flex items-center gap-4 p-4">
            <div className="flex h-12 w-12 items-center justify-center rounded-full bg-red-100">
              <XCircle className="h-6 w-6 text-red-600" />
            </div>
            <div>
              <p className="text-2xl font-bold text-red-600">{failCount}</p>
              <p className="text-sm text-muted-foreground">Requirements Failed</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Requirements & Extensions - Two Column Layout */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Requirements Check */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5" />
              System Requirements
            </CardTitle>
            <CardDescription>
              Minimum requirements for Swift Commerce to run properly
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {requirements.map((req, index) => (
              <RequirementRow key={index} req={req} />
            ))}
          </CardContent>
        </Card>

        {/* PHP Extensions */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Code2 className="h-5 w-5" />
              PHP Extensions
            </CardTitle>
            <CardDescription>
              Required and recommended PHP extensions
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <h4 className="text-sm font-medium mb-3">Required Extensions</h4>
              <div className="flex flex-wrap gap-2">
                {extensionStatus.map((ext) => (
                  <Badge 
                    key={ext.name}
                    variant="outline"
                    className={ext.installed 
                      ? 'bg-green-100 text-green-800 border-green-200' 
                      : 'bg-red-100 text-red-800 border-red-200'
                    }
                  >
                    {ext.installed ? <CheckCircle2 className="h-3 w-3 mr-1" /> : <XCircle className="h-3 w-3 mr-1" />}
                    {ext.name}
                  </Badge>
                ))}
              </div>
            </div>
            <div>
              <h4 className="text-sm font-medium mb-3">Recommended Extensions</h4>
              <div className="flex flex-wrap gap-2">
                {recommendedStatus.map((ext) => (
                  <Badge 
                    key={ext.name}
                    variant="outline"
                    className={ext.installed 
                      ? 'bg-green-100 text-green-800 border-green-200' 
                      : 'bg-yellow-100 text-yellow-800 border-yellow-200'
                    }
                  >
                    {ext.installed ? <CheckCircle2 className="h-3 w-3 mr-1" /> : <AlertTriangle className="h-3 w-3 mr-1" />}
                    {ext.name}
                  </Badge>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        {/* Registration Forms Diagnostics */}
        <Card className={systemInfo.registrationForms.warnings.length > 0 ? 'border-yellow-200 bg-yellow-50/40' : ''}>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <UserPlus className="h-5 w-5" />
              Registration Forms
            </CardTitle>
            <CardDescription>
              Checks that affect WordPress and WooCommerce registration field rendering
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-1">
            {systemInfo.registrationForms.warnings.length > 0 && (
              <div className="mb-3 rounded-lg border border-yellow-200 bg-yellow-50 p-3">
                <div className="flex items-center gap-2 text-sm font-medium text-yellow-800">
                  <AlertTriangle className="h-4 w-4" />
                  Warnings
                </div>
                <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-yellow-800">
                  {systemInfo.registrationForms.warnings.map((warning) => (
                    <li key={warning}>{warning}</li>
                  ))}
                </ul>
              </div>
            )}
            <InfoRow label="WP Users Can Register" value={systemInfo.registrationForms.wordpress.usersCanRegister} />
            <InfoRow label="WP Active Owner" value={systemInfo.registrationForms.wordpress.activeOwner} />
            <InfoRow label="WP register_form Callbacks" value={systemInfo.registrationForms.wordpress.registerFormHookCallbacks} />
            <InfoRow label="Woo My Account Registration" value={systemInfo.registrationForms.woocommerce.myAccountRegistrationEnabled} />
            <InfoRow label="Woo Active Owner" value={systemInfo.registrationForms.woocommerce.activeOwner} />
            <InfoRow label="Woo Register Hook Callbacks" value={systemInfo.registrationForms.woocommerce.woocommerceRegisterFormHookCallbacks} />
            <InfoRow label="My Account Page ID" value={systemInfo.registrationForms.woocommerce.myAccountPageId || 'Not assigned'} />
            <InfoRow label="My Account Uses Shortcode" value={systemInfo.registrationForms.woocommerce.myAccountPageUsesShortcode} />
            <InfoRow label="My Account Uses Block" value={systemInfo.registrationForms.woocommerce.myAccountPageUsesBlock} />
            <InfoRow label="Theme Template Override" value={systemInfo.registrationForms.woocommerce.themeTemplateOverride || 'None'} mono />
            <InfoRow label="Form Owner Mode" value={systemInfo.registrationForms.conflict.registrationFormMode} />
          </CardContent>
        </Card>

        {/* WordPress Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Globe className="h-5 w-5" />
              WordPress Environment
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="Version" value={systemInfo.wordpress.version} />
            <InfoRow label="Multisite" value={systemInfo.wordpress.multisite} />
            <InfoRow label="Memory Limit" value={systemInfo.wordpress.memoryLimit} />
            <InfoRow label="Debug Mode" value={systemInfo.wordpress.debugMode} />
            <InfoRow label="WP Cron" value={systemInfo.wordpress.cron} />
            <InfoRow label="Language" value={systemInfo.wordpress.language} />
            <InfoRow label="Timezone" value={systemInfo.wordpress.timezone} />
            <InfoRow label="Permalink Structure" value={systemInfo.wordpress.permalinkStructure} mono />
          </CardContent>
        </Card>

        {/* PHP Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Code2 className="h-5 w-5" />
              PHP Configuration
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="Version" value={systemInfo.php.version} />
            <InfoRow label="Memory Limit" value={systemInfo.php.memoryLimit} />
            <InfoRow label="Max Execution Time" value={`${systemInfo.php.maxExecutionTime}s`} />
            <InfoRow label="Max Input Vars" value={systemInfo.php.maxInputVars} />
            <InfoRow label="Post Max Size" value={systemInfo.php.postMaxSize} />
            <InfoRow label="Upload Max Filesize" value={systemInfo.php.uploadMaxFilesize} />
            <InfoRow label="Safe Mode" value={systemInfo.php.safeMode} />
            <InfoRow label="Open Basedir" value={systemInfo.php.openBasedir} />
          </CardContent>
        </Card>

        {/* MySQL Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Database className="h-5 w-5" />
              Database
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="MySQL Version" value={systemInfo.mysql.version} />
            <InfoRow label="Max Connections" value={systemInfo.mysql.maxConnections} />
            <InfoRow label="Max Packet Size" value={systemInfo.mysql.maxPacketSize} />
            <InfoRow label="Storage Engine" value={systemInfo.mysql.storageEngine} />
          </CardContent>
        </Card>

        {/* Server Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Server className="h-5 w-5" />
              Server
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="Software" value={systemInfo.server.software} />
            <InfoRow label="Protocol" value={systemInfo.server.serverProtocol} />
            <InfoRow label="Document Root" value={systemInfo.server.documentRoot} mono />
            <InfoRow label="Server IP" value={systemInfo.server.serverAddress} mono />
          </CardContent>
        </Card>

        {/* WooCommerce Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <ShoppingCart className="h-5 w-5" />
              WooCommerce
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="Version" value={systemInfo.woocommerce.version || 'Not Installed'} />
            <InfoRow label="Database Version" value={systemInfo.woocommerce.databaseVersion || 'N/A'} />
            <InfoRow label="Currency" value={systemInfo.woocommerce.currency || 'N/A'} />
            <InfoRow label="Products" value={systemInfo.woocommerce.productsCount} />
            <InfoRow label="Orders" value={systemInfo.woocommerce.ordersCount} />
          </CardContent>
        </Card>

        {/* Swift Commerce Info */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Zap className="h-5 w-5" />
              Swift Commerce
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-1">
            <InfoRow label="Free Plugin Version" value={systemInfo.swiftCommerce.version || '1.0.0'} />
            {systemInfo.swiftCommerce.proVersion && (
              <InfoRow label="Pro Plugin Version" value={systemInfo.swiftCommerce.proVersion} />
            )}
            <div className="py-2.5 px-4">
              <span className="text-muted-foreground">Enabled Features</span>
              <div className="flex flex-wrap gap-1 mt-2">
                {systemInfo.swiftCommerce.featuresEnabled.length > 0 ? (
                  systemInfo.swiftCommerce.featuresEnabled.map((feature) => (
                    <Badge key={feature} variant="secondary" className="text-xs">
                      {feature}
                    </Badge>
                  ))
                ) : (
                  <span className="text-sm text-muted-foreground">No features enabled yet</span>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
