"use client"

import { useState } from "react"
import { router } from "@inertiajs/react"
import { Button } from "../../Components/UI/Button"
import { Card, CardContent } from "../../Components/UI/Card"
import {
  CheckCircle2,
  XCircle,
  ArrowRight,
  ArrowLeft,
  Server,
  HardDrive,
  Shield,
  AlertCircle
} from "lucide-react"
import { motion } from "framer-motion"

export default function Requirements({ 
  requirements = {}, 
  permissions = {}, 
  phpSupportInfo = {},
  appName = "Postuno" 
}) {
  const [isLoading, setIsLoading] = useState(false)

  // Check if all requirements are met
  const checkAllRequirements = () => {
    // Check PHP requirements
    if (!phpSupportInfo.supported) return false;
    
    // Check PHP extensions
    if (requirements.requirements && requirements.requirements.php) {
      const phpExtensions = requirements.requirements.php;
      if (!Object.values(phpExtensions).every(ext => ext === true)) return false;
    }
    
    // Check permissions 
    if (permissions && Object.keys(permissions).length > 0) {
      if (!Object.values(permissions).every(perm => perm === true)) return false;
    }
    
    return true;
  };

  const allRequirementsMet = checkAllRequirements();

  const handleNext = () => {
    if (allRequirementsMet) {
      setIsLoading(true)
      // Skip Envato verification and go directly to database setup
      router.visit("/install/db-setup?verify_token=" + btoa("dbsetup_"), {
        method: 'get',
        data: { system_requirments: true }
      })
    }
  }

  const handleBack = () => {
    router.visit("/install")
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900">
      <div className="container mx-auto px-4 py-12">
        <div className="max-w-4xl mx-auto">
          {/* Header */}
          <motion.div 
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            className="text-center mb-12"
          >
            <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 mb-6">
              <Server className="w-10 h-10 text-white" />
            </div>
            <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
              System Requirements
            </h1>
            <p className="text-lg text-gray-600 dark:text-gray-400">
              Checking if your server meets all requirements
            </p>
          </motion.div>

          {/* Progress Bar */}
          <div className="mb-8">
            <div className="flex items-center justify-between mb-2">
              <span className="text-sm text-gray-600 dark:text-gray-400">Installation Progress</span>
              <span className="text-sm text-gray-600 dark:text-gray-400">Step 1 of 6</span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700">
              <div className="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full transition-all duration-500" style={{ width: '17%' }}></div>
            </div>
          </div>

          {/* Main Card */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
          >
            <Card className="backdrop-blur-sm bg-white/90 dark:bg-gray-800/90 shadow-xl border-0">
              <CardContent className="p-8">
                {/* PHP Version Check */}
                <div className="mb-8">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                    <Shield className="w-5 h-5 mr-2" />
                    PHP Version
                  </h3>
                  <div className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-medium text-gray-700 dark:text-gray-300">
                          PHP {phpSupportInfo.current || "Unknown"}
                        </p>
                        <p className="text-sm text-gray-500 dark:text-gray-400">
                          Minimum required: PHP {phpSupportInfo.minimum || "8.1"}
                        </p>
                      </div>
                      {phpSupportInfo.supported ? (
                        <CheckCircle2 className="w-6 h-6 text-green-500" />
                      ) : (
                        <XCircle className="w-6 h-6 text-red-500" />
                      )}
                    </div>
                  </div>
                </div>

                {/* PHP Extensions */}
                <div className="mb-8">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                    <HardDrive className="w-5 h-5 mr-2" />
                    PHP Extensions
                  </h3>
                  <div className="grid md:grid-cols-2 gap-4">
                    {requirements.requirements && requirements.requirements.php ? (
                      Object.entries(requirements.requirements.php).map(([extension, isInstalled]) => (
                        <motion.div
                          key={extension}
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          className="bg-gray-50 dark:bg-gray-900/50 rounded-lg p-4"
                        >
                          <div className="flex items-center justify-between">
                            <span className="text-gray-700 dark:text-gray-300 font-medium">
                              {extension}
                            </span>
                            {isInstalled ? (
                              <CheckCircle2 className="w-5 h-5 text-green-500" />
                            ) : (
                              <XCircle className="w-5 h-5 text-red-500" />
                            )}
                          </div>
                        </motion.div>
                      ))
                    ) : (
                      <p className="text-gray-500 dark:text-gray-400">No PHP extension requirements found.</p>
                    )}
                  </div>
                </div>

                {/* File Permissions */}
                <div className="mb-8">
                  <h3 className="font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
                    <Shield className="w-5 h-5 mr-2" />
                    File Permissions
                  </h3>
                  <div className="space-y-3">
                    {permissions && Object.keys(permissions).length > 0 ? Object.entries(permissions).map(([path, isWritable]) => {
                      // Define what each permission is for
                      const getPermissionInfo = (path) => {
                        switch(path) {
                          case 'storage':
                          case 'storage/':
                            return {
                              purpose: 'Stores logs, cache, sessions, uploaded files',
                              required: '775',
                              critical: true
                            }
                          case 'bootstrap/cache':
                          case 'bootstrap/cache/':
                            return {
                              purpose: 'Laravel compiled views and route cache',
                              required: '775', 
                              critical: true
                            }
                          case 'public':
                          case 'public/':
                            return {
                              purpose: 'Web accessible files and user uploads',
                              required: '775',
                              critical: false
                            }
                          case '.env':
                            return {
                              purpose: 'Environment configuration file',
                              required: '644',
                              critical: true
                            }
                          default:
                            return {
                              purpose: 'Application files',
                              required: '775',
                              critical: false
                            }
                        }
                      }
                      
                      const permInfo = getPermissionInfo(path)
                      
                      return (
                        <motion.div
                          key={path}
                          initial={{ opacity: 0, x: -20 }}
                          animate={{ opacity: 1, x: 0 }}
                          className={`rounded-lg p-4 border-l-4 ${
                            isWritable 
                              ? 'bg-green-50 dark:bg-green-900/20 border-l-green-500' 
                              : 'bg-red-50 dark:bg-red-900/20 border-l-red-500'
                          }`}
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex-1">
                              <div className="flex items-center space-x-3 mb-2">
                                <p className="font-semibold text-gray-900 dark:text-white">
                                  {path}
                                </p>
                                {isWritable ? (
                                  <div className="flex items-center space-x-1">
                                    <CheckCircle2 className="w-4 h-4 text-green-500" />
                                    <span className="text-xs font-medium text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/30 px-2 py-1 rounded">
                                      WRITABLE [{path}]
                                    </span>
                                  </div>
                                ) : (
                                  <div className="flex items-center space-x-1">
                                    <XCircle className="w-4 h-4 text-red-500" />
                                    <span className="text-xs font-medium text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/30 px-2 py-1 rounded">
                                      NOT WRITABLE [{path}]
                                    </span>
                                  </div>
                                )}
                              </div>
                              
                              <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                                📁 <strong>Purpose:</strong> {permInfo.purpose}
                              </p>
                              
                              <p className="text-xs text-gray-500 dark:text-gray-500">
                                🔐 <strong>Required Permission:</strong> {permInfo.required}
                                {permInfo.critical && (
                                  <span className="ml-2 text-orange-600 dark:text-orange-400 font-medium">
                                    (Critical)
                                  </span>
                                )}
                              </p>
                            </div>
                          </div>
                        </motion.div>
                      )
                    }) : (
                      <p className="text-gray-500 dark:text-gray-400">No permission requirements found.</p>
                    )}
                  </div>
                </div>

                {/* Status Message */}
                {!allRequirementsMet && (
                  <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
                    <div className="flex items-start">
                      <AlertCircle className="w-5 h-5 text-red-500 mt-0.5 mr-3" />
                      <div>
                        <p className="text-red-800 dark:text-red-300 font-medium">
                          Requirements Not Met
                        </p>
                        <p className="text-red-600 dark:text-red-400 text-sm mt-1">
                          Please resolve all issues before proceeding with the installation.
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {/* Platform-Specific Permission Help Section */}
                {Object.values(permissions).some(p => !p) && (
                  <div className="mb-6 p-6 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                    <h4 className="font-semibold text-blue-800 dark:text-blue-300 mb-4 text-lg">
                      🔧 Fix File Permissions - Choose Your Platform
                    </h4>
                    
                    {/* Platform Tabs */}
                    <div className="space-y-6">
                      
                      {/* Mac/Linux Terminal */}
                      <div className="bg-white dark:bg-zinc-900/50 rounded-lg p-4 shadow-sm">
                        <h5 className="font-semibold text-gray-800 dark:text-gray-200 mb-3 flex items-center">
                          💻 Mac / Linux Terminal
                        </h5>
                        <div className="space-y-2">
                          <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                            Open Terminal and navigate to your project folder, then run:
                          </p>
                          <div className="bg-gray-100 dark:bg-gray-900 rounded p-3 font-mono text-sm overflow-x-auto">
                            <div className="space-y-1 text-gray-800 dark:text-gray-200">
                              <p><span className="text-blue-600">cd</span> /path/to/your/project</p>
                              <p><span className="text-green-600">chmod</span> -R 775 storage</p>
                              <p><span className="text-green-600">chmod</span> -R 775 bootstrap/cache</p>
                              <p><span className="text-green-600">chmod</span> -R 775 public</p>
                              <p><span className="text-green-600">chmod</span> 644 .env</p>
                            </div>
                          </div>
                          <p className="text-xs text-gray-500 dark:text-gray-400">
                            💡 One-liner: <code className="bg-gray-200 dark:bg-gray-700 px-1 rounded text-xs">chmod -R 775 storage bootstrap/cache public && chmod 644 .env</code>
                          </p>
                        </div>
                      </div>

                      {/* Windows */}
                      <div className="bg-white dark:bg-zinc-900/50 rounded-lg p-4 shadow-sm">
                        <h5 className="font-semibold text-gray-800 dark:text-gray-200 mb-3 flex items-center">
                          🪟 Windows
                        </h5>
                        <div className="space-y-3">
                          <div>
                            <p className="font-medium text-sm text-gray-700 dark:text-gray-300">Option 1: Using WSL/Git Bash</p>
                            <div className="bg-gray-100 dark:bg-gray-900 rounded p-3 font-mono text-sm mt-1">
                              <p className="text-gray-800 dark:text-gray-200">Same commands as Mac/Linux above</p>
                            </div>
                          </div>
                          <div>
                            <p className="font-medium text-sm text-gray-700 dark:text-gray-300">Option 2: File Explorer</p>
                            <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-1 ml-4">
                              <li>• Right-click each folder → Properties → Security</li>
                              <li>• Give "Full Control" to IIS_IUSRS or IUSR</li>
                              <li>• Apply to folders: storage, bootstrap/cache, public</li>
                            </ul>
                          </div>
                        </div>
                      </div>

                      {/* cPanel File Manager */}
                      <div className="bg-white dark:bg-zinc-900/50 rounded-lg p-4 shadow-sm">
                        <h5 className="font-semibold text-gray-800 dark:text-gray-200 mb-3 flex items-center">
                          🌐 cPanel File Manager
                        </h5>
                        <div className="space-y-2">
                          <ol className="text-sm text-gray-600 dark:text-gray-400 space-y-1">
                            <li>1. Login to cPanel → File Manager</li>
                            <li>2. Navigate to your website folder</li>
                            <li>3. Right-click folder → Change Permissions</li>
                            <li>4. Set permissions:</li>
                            <div className="ml-4 mt-2 bg-gray-100 dark:bg-gray-900 rounded p-2 text-xs">
                              <p><strong>storage/</strong> → 775 (Check: Owner RWX, Group RWX, Public RX)</p>
                              <p><strong>bootstrap/cache/</strong> → 775</p>
                              <p><strong>public/</strong> → 775</p>
                              <p><strong>.env</strong> → 644 (Check: Owner RW, Group R, Public R)</p>
                            </div>
                          </ol>
                        </div>
                      </div>

                      {/* Server SSH */}
                      <div className="bg-white dark:bg-zinc-900/50 rounded-lg p-4 shadow-sm">
                        <h5 className="font-semibold text-gray-800 dark:text-gray-200 mb-3 flex items-center">
                          🖥️ Server SSH
                        </h5>
                        <div className="space-y-2">
                          <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                            SSH into your server and run:
                          </p>
                          <div className="bg-gray-100 dark:bg-gray-900 rounded p-3 font-mono text-sm">
                            <div className="space-y-1 text-gray-800 dark:text-gray-200">
                              <p><span className="text-blue-600">ssh</span> user@your-server.com</p>
                              <p><span className="text-blue-600">cd</span> /var/www/html/your-project</p>
                              <p><span className="text-green-600">sudo chmod</span> -R 775 storage bootstrap/cache public</p>
                              <p><span className="text-green-600">sudo chmod</span> 644 .env</p>
                              <p><span className="text-orange-600">sudo chown</span> -R www-data:www-data storage bootstrap/cache public</p>
                            </div>
                          </div>
                        </div>
                      </div>

                      {/* FTP Client */}
                      <div className="bg-white dark:bg-zinc-900/50 rounded-lg p-4 shadow-sm">
                        <h5 className="font-semibold text-gray-800 dark:text-gray-200 mb-3 flex items-center">
                          📁 FTP Client (FileZilla, WinSCP)
                        </h5>
                        <div className="space-y-2">
                          <ol className="text-sm text-gray-600 dark:text-gray-400 space-y-1">
                            <li>1. Connect to your server via FTP</li>
                            <li>2. Right-click folder → File Permissions/Properties</li>
                            <li>3. Set numeric permissions:</li>
                            <div className="ml-4 mt-2 bg-gray-100 dark:bg-gray-900 rounded p-2 text-xs font-mono">
                              <p><strong>storage/</strong> = 775</p>
                              <p><strong>bootstrap/cache/</strong> = 775</p>
                              <p><strong>public/</strong> = 775</p>
                              <p><strong>.env</strong> = 644</p>
                            </div>
                          </ol>
                        </div>
                      </div>
                    </div>
                    
                    <div className="mt-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded">
                      <p className="text-sm text-yellow-800 dark:text-yellow-200">
                        ⚡ <strong>Quick Tip:</strong> After fixing permissions, refresh this page to see updated status.
                        If you're still having issues, contact your hosting provider for assistance.
                      </p>
                    </div>
                  </div>
                )}

                {allRequirementsMet && (
                  <div className="mb-6 p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
                    <div className="flex items-start">
                      <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 mr-3" />
                      <div>
                        <p className="text-green-800 dark:text-green-300 font-medium">
                          All Requirements Met
                        </p>
                        <p className="text-green-600 dark:text-green-400 text-sm mt-1">
                          Your server meets all requirements. You can proceed with the installation.
                        </p>
                      </div>
                    </div>
                  </div>
                )}

                {/* Action Buttons */}
                <div className="flex gap-4">
                  <Button
                    onClick={handleBack}
                    variant="outline"
                    className="flex-1"
                  >
                    <ArrowLeft className="mr-2 h-4 w-4" />
                    Back
                  </Button>
                  <Button
                    onClick={handleNext}
                    disabled={!allRequirementsMet || isLoading}
                    className="flex-1 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white"
                  >
                    {isLoading ? (
                      <span className="flex items-center justify-center">
                        <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                      </span>
                    ) : (
                      <span className="flex items-center justify-center">
                        Next Step
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </span>
                    )}
                  </Button>
                </div>
              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    </div>
  )
}