import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { 
  Server, 
  Database, 
  Settings, 
  Shield, 
  Download, 
  Copy, 
  CheckCircle, 
  AlertTriangle,
  FileText,
  Terminal,
  Globe,
  Lock,
  Zap,
  HardDrive,
  Monitor,
  Code
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function CpanelInstallation() {
  const [copiedStep, setCopiedStep] = useState<string | null>(null);
  const { toast } = useToast();

  const copyToClipboard = async (text: string, stepId: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedStep(stepId);
      toast({
        title: "Copied to clipboard",
        description: "Command copied successfully",
      });
      setTimeout(() => setCopiedStep(null), 2000);
    } catch (error) {
      toast({
        title: "Copy failed",
        description: "Could not copy to clipboard",
        variant: "destructive",
      });
    }
  };

  const CodeBlock = ({ code, stepId }: { code: string; stepId: string }) => (
    <div className="relative bg-gray-900 text-gray-100 p-4 rounded-lg mt-2 font-mono text-sm">
      <pre className="overflow-x-auto">{code}</pre>
      <Button
        size="sm"
        variant="outline"
        className="absolute top-2 right-2 h-6 w-6 p-0"
        onClick={() => copyToClipboard(code, stepId)}
      >
        {copiedStep === stepId ? (
          <CheckCircle className="h-3 w-3 text-green-500" />
        ) : (
          <Copy className="h-3 w-3" />
        )}
      </Button>
    </div>
  );

  return (
    <div className="p-6 max-w-6xl mx-auto">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center space-x-3 mb-4">
          <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-lg flex items-center justify-center">
            <Server className="h-6 w-6 text-white" />
          </div>
          <div>
            <h1 className="text-3xl font-bold text-gray-900">cPanel Installation Guide</h1>
            <p className="text-gray-600">Complete step-by-step guide for hosting SportsPro on cPanel</p>
          </div>
        </div>
        
        <Alert className="bg-blue-50 border-blue-200">
          <Shield className="h-4 w-4 text-blue-600" />
          <AlertDescription className="text-blue-800">
            This guide will help you install SportsPro on your personal hosting account using cPanel. 
            Follow each step carefully for a successful deployment.
          </AlertDescription>
        </Alert>
      </div>

      <Tabs defaultValue="prerequisites" className="space-y-6">
        <TabsList className="grid w-full grid-cols-6">
          <TabsTrigger value="prerequisites">Prerequisites</TabsTrigger>
          <TabsTrigger value="setup">Setup</TabsTrigger>
          <TabsTrigger value="database">Database</TabsTrigger>
          <TabsTrigger value="deployment">Deployment</TabsTrigger>
          <TabsTrigger value="configuration">Configuration</TabsTrigger>
          <TabsTrigger value="maintenance">Maintenance</TabsTrigger>
        </TabsList>

        {/* Prerequisites Tab */}
        <TabsContent value="prerequisites">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Settings className="h-5 w-5" />
                  <span>Server Requirements</span>
                </CardTitle>
                <CardDescription>Ensure your hosting environment meets these requirements</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Node.js Version</span>
                      <Badge variant="outline">18.x or higher</Badge>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">PostgreSQL</span>
                      <Badge variant="outline">12+ required</Badge>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Memory (RAM)</span>
                      <Badge variant="outline">2GB recommended</Badge>
                    </div>
                  </div>
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">Storage Space</span>
                      <Badge variant="outline">2GB minimum</Badge>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">SSL Certificate</span>
                      <Badge variant="outline">Required</Badge>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <span className="font-medium">SSH Access</span>
                      <Badge variant="outline">Recommended</Badge>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Monitor className="h-5 w-5" />
                  <span>cPanel Requirements</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-green-500" />
                    <span>cPanel with Node.js support enabled</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-green-500" />
                    <span>File Manager access</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-green-500" />
                    <span>Database management tools</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-green-500" />
                    <span>Domain management access</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Setup Tab */}
        <TabsContent value="setup">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Server className="h-5 w-5" />
                  <span>Step 1: Verify Node.js Support</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <ol className="space-y-3 list-decimal list-inside">
                  <li>Log into your cPanel dashboard</li>
                  <li>Look for "Node.js" or "Node.js App" in the Software section</li>
                  <li>Click on Node.js App to verify version 18.x or higher is available</li>
                  <li>If not available, contact your hosting provider to enable Node.js</li>
                </ol>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Download className="h-5 w-5" />
                  <span>Step 2: Upload Application Files</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="bg-yellow-50 border border-yellow-200 p-4 rounded-lg">
                  <div className="flex items-center space-x-2 mb-2">
                    <AlertTriangle className="h-4 w-4 text-yellow-600" />
                    <span className="font-medium text-yellow-800">Method A: File Manager (Recommended)</span>
                  </div>
                  <ol className="space-y-2 list-decimal list-inside text-sm text-yellow-800">
                    <li>Go to cPanel → File Manager</li>
                    <li>Navigate to public_html directory</li>
                    <li>Create new folder: <code className="bg-yellow-100 px-1 rounded">sportspro</code></li>
                    <li>Upload and extract SportsPro ZIP file</li>
                  </ol>
                </div>

                <div className="bg-blue-50 border border-blue-200 p-4 rounded-lg">
                  <div className="flex items-center space-x-2 mb-2">
                    <Terminal className="h-4 w-4 text-blue-600" />
                    <span className="font-medium text-blue-800">Method B: SSH (Advanced)</span>
                  </div>
                  <CodeBlock 
                    code={`ssh username@yourdomain.com
cd public_html
mkdir sportspro
cd sportspro
# Upload files or clone repository`}
                    stepId="ssh-setup"
                  />
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Database Tab */}
        <TabsContent value="database">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Database className="h-5 w-5" />
                  <span>PostgreSQL Database Setup</span>
                </CardTitle>
                <CardDescription>Create and configure your database</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <h4 className="font-semibold">Step 1: Create Database</h4>
                  <ol className="space-y-2 list-decimal list-inside">
                    <li>Go to cPanel → Databases → PostgreSQL Databases</li>
                    <li>Create new database: <code className="bg-gray-100 px-2 py-1 rounded">sportspro_db</code></li>
                    <li>Create database user: <code className="bg-gray-100 px-2 py-1 rounded">sportspro_user</code></li>
                    <li>Generate strong password for the user</li>
                    <li>Grant ALL PRIVILEGES to sportspro_user for sportspro_db</li>
                  </ol>
                </div>

                <div className="bg-gray-50 p-4 rounded-lg">
                  <h5 className="font-medium mb-2">Connection Details Template:</h5>
                  <CodeBlock 
                    code={`Host: localhost
Port: 5432
Database: sportspro_db
Username: sportspro_user
Password: [your_secure_password]`}
                    stepId="db-connection"
                  />
                </div>

                <Alert>
                  <Shield className="h-4 w-4" />
                  <AlertDescription>
                    Save these database credentials securely - you'll need them for environment configuration.
                  </AlertDescription>
                </Alert>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Deployment Tab */}
        <TabsContent value="deployment">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Zap className="h-5 w-5" />
                  <span>Configure Node.js Application</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-4">
                  <h4 className="font-semibold">Application Settings</h4>
                  <div className="bg-gray-50 p-4 rounded-lg">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="font-medium">Node.js Version:</span>
                        <code className="ml-2 bg-gray-200 px-2 py-1 rounded">18.x</code>
                      </div>
                      <div>
                        <span className="font-medium">Application Mode:</span>
                        <code className="ml-2 bg-gray-200 px-2 py-1 rounded">Production</code>
                      </div>
                      <div>
                        <span className="font-medium">Application Root:</span>
                        <code className="ml-2 bg-gray-200 px-2 py-1 rounded">public_html/sportspro</code>
                      </div>
                      <div>
                        <span className="font-medium">Startup File:</span>
                        <code className="ml-2 bg-gray-200 px-2 py-1 rounded">server/index.js</code>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <h4 className="font-semibold">Install Dependencies</h4>
                  <CodeBlock 
                    code={`npm install --production
npm run build`}
                    stepId="npm-install"
                  />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <FileText className="h-5 w-5" />
                  <span>Environment Configuration</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="mb-4">Create <code className="bg-gray-100 px-2 py-1 rounded">.env</code> file in application root:</p>
                <CodeBlock 
                  code={`# Database Configuration
DATABASE_URL=postgresql://sportspro_user:YOUR_PASSWORD@localhost:5432/sportspro_db

# Session Configuration
SESSION_SECRET=your_super_secret_key_minimum_32_characters_long

# Application Settings
NODE_ENV=production
PORT=3000

# Domain Configuration
DOMAIN=yourdomain.com
PROTOCOL=https

# Email Configuration (Optional)
SENDGRID_API_KEY=your_sendgrid_api_key_here`}
                  stepId="env-config"
                />
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Configuration Tab */}
        <TabsContent value="configuration">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Globe className="h-5 w-5" />
                  <span>Domain & SSL Setup</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-4">
                  <h4 className="font-semibold">SSL Configuration</h4>
                  <ol className="space-y-2 list-decimal list-inside">
                    <li>Go to cPanel → Security → SSL/TLS</li>
                    <li>Install SSL certificate for your domain</li>
                    <li>Enable "Force HTTPS Redirect"</li>
                    <li>Test HTTPS access: <code className="bg-gray-100 px-2 py-1 rounded">https://yourdomain.com/sportspro</code></li>
                  </ol>
                </div>

                <div className="space-y-4">
                  <h4 className="font-semibold">Performance Optimization</h4>
                  <p>Create <code className="bg-gray-100 px-2 py-1 rounded">.htaccess</code> file:</p>
                  <CodeBlock 
                    code={`# Enable Gzip Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Browser Caching
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
</IfModule>`}
                    stepId="htaccess"
                  />
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Lock className="h-5 w-5" />
                  <span>Security Hardening</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-3">
                  <h4 className="font-semibold">File Permissions</h4>
                  <CodeBlock 
                    code={`chmod 644 .env
chmod 755 server/
chmod 644 package.json`}
                    stepId="permissions"
                  />
                </div>

                <div className="space-y-3">
                  <h4 className="font-semibold">Default Login Credentials</h4>
                  <div className="bg-red-50 border border-red-200 p-4 rounded-lg">
                    <div className="flex items-center space-x-2 mb-2">
                      <AlertTriangle className="h-4 w-4 text-red-600" />
                      <span className="font-medium text-red-800">Important: Change Default Password</span>
                    </div>
                    <div className="text-sm text-red-800">
                      <p>Default Super Admin Login:</p>
                      <ul className="list-disc list-inside mt-2">
                        <li>Email: admin@sportspro.com</li>
                        <li>Password: superadmin123</li>
                      </ul>
                      <p className="mt-2 font-medium">Change this password immediately after first login!</p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* Maintenance Tab */}
        <TabsContent value="maintenance">
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <HardDrive className="h-5 w-5" />
                  <span>Backup & Maintenance</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <h4 className="font-semibold">Regular Backup Commands</h4>
                  <CodeBlock 
                    code={`# Database backup
pg_dump sportspro_db > backup_$(date +%Y%m%d).sql

# Update dependencies
npm update
npm audit fix`}
                    stepId="backup"
                  />
                </div>

                <div className="space-y-4">
                  <h4 className="font-semibold">Monitoring & Troubleshooting</h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="bg-gray-50 p-4 rounded-lg">
                      <h5 className="font-medium mb-2">Common Issues</h5>
                      <ul className="text-sm space-y-1">
                        <li>• Node.js app won't start</li>
                        <li>• Database connection failed</li>
                        <li>• Build errors</li>
                        <li>• Permission errors</li>
                      </ul>
                    </div>
                    <div className="bg-gray-50 p-4 rounded-lg">
                      <h5 className="font-medium mb-2">Log Locations</h5>
                      <ul className="text-sm space-y-1">
                        <li>• Node.js App manager logs</li>
                        <li>• cPanel → Error Logs</li>
                        <li>• Raw Access Logs</li>
                        <li>• Application console logs</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* Quick Access Actions */}
      <Card className="mt-8">
        <CardHeader>
          <CardTitle>Quick Actions</CardTitle>
          <CardDescription>Download installation resources and access support</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex flex-wrap gap-3">
            <Button variant="outline" className="flex items-center space-x-2">
              <Download className="h-4 w-4" />
              <span>Download Application</span>
            </Button>
            <Button variant="outline" className="flex items-center space-x-2">
              <FileText className="h-4 w-4" />
              <span>Environment Template</span>
            </Button>
            <Button variant="outline" className="flex items-center space-x-2">
              <Code className="h-4 w-4" />
              <span>Configuration Examples</span>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}