"use client"

import { useState } from "react"
import { router, useForm } from "@inertiajs/react"
import { Button } from "../../Components/UI/Button"
import { Card, CardContent } from "../../Components/UI/Card"
import { Input } from "../../Components/UI/Input"
import { Label } from "../../Components/UI/Label"
import {
  Database,
  ArrowRight,
  ArrowLeft,
  Server,
  AlertCircle,
  CheckCircle2,
  Lock,
  User,
  Globe
} from "lucide-react"
import { motion } from "framer-motion"

export default function DatabaseSetup({ appName = "Postuno", errors = {}, flash = {}, old = {} }) {
  const { data, setData, post, processing } = useForm({
    db_host: old.db_host || 'localhost',
    db_port: old.db_port || '3306',
    db_name: old.db_name || '',
    db_user: old.db_user || '',
    db_password: '' // Never pre-fill password for security
  })

  const [testingConnection, setTestingConnection] = useState(false)
  const [connectionStatus, setConnectionStatus] = useState(null)
  const [connectionError, setConnectionError] = useState(null)

  const handleSubmit = (e) => {
    e.preventDefault()
    post('/install/db-store')
  }

  const handleTestConnection = async () => {
    setTestingConnection(true)
    setConnectionStatus(null)
    setConnectionError(null)

    try {
      // Get CSRF token
      const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')

      if (!csrfToken) {
        throw new Error('CSRF token not found')
      }

      const response = await fetch('/install/db-test-connection', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-TOKEN': csrfToken,
          'Accept': 'application/json',
        },
        body: JSON.stringify({
          db_host: data.db_host,
          db_port: data.db_port,
          db_name: data.db_name,
          db_user: data.db_user,
          db_password: data.db_password
        })
      })

      if (!response.ok) {
        if (response.status === 419) {
          throw new Error('Session expired. Please refresh the page and try again.')
        }
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()

      if (result.success) {
        setConnectionStatus('success')
      } else {
        setConnectionStatus('error')
        setConnectionError(result.error || 'Connection failed')
      }
    } catch (error) {
      setConnectionStatus('error')
      setConnectionError(error.message || 'Network error: Unable to test connection')
    } finally {
      setTestingConnection(false)
    }
  }

  const handleBack = () => {
    router.visit('/install/requirement-verification?verify_token=' + btoa('requirements'))
  }

  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">
              <Database className="w-10 h-10 text-white" />
            </div>
            <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
              Database Configuration
            </h1>
            <p className="text-lg text-gray-600 dark:text-gray-400">
              Configure your database connection for {appName}
            </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 2 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: '33%' }}></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">
                <form onSubmit={handleSubmit} className="space-y-6">
                  {/* Professional Error/Success Message Display */}
                  {(flash.error || flash.success || errors.general) && (
                    <div className={`mb-6 p-4 border rounded-lg ${
                      flash.success
                        ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                        : 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
                    }`}>
                      <div className="flex items-start">
                        {flash.success ? (
                          <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 mr-3" />
                        ) : (
                          <AlertCircle className="w-5 h-5 text-red-500 mt-0.5 mr-3" />
                        )}
                        <div>
                          <h4 className={`font-medium ${
                            flash.success
                              ? 'text-green-800 dark:text-green-200'
                              : 'text-red-800 dark:text-red-200'
                          }`}>
                            {flash.success ? 'Success' : 'Database Configuration Issue'}
                          </h4>
                          <p className={`text-sm mt-1 ${
                            flash.success
                              ? 'text-green-600 dark:text-green-300'
                              : 'text-red-600 dark:text-red-300'
                          }`}>
                            {flash.success || flash.error || errors.general || 'Please check your database configuration and try again.'}
                          </p>
                          {!flash.success && (
                            <div className="mt-3 text-xs text-gray-600 dark:text-gray-400">
                              <p><strong>Common solutions:</strong></p>
                              <ul className="list-disc list-inside mt-1 space-y-1">
                                <li>Verify your database credentials are correct</li>
                                <li>Ensure the database exists on your server</li>
                                <li>Check that your database server is running</li>
                                <li>Confirm the database user has proper permissions</li>
                              </ul>
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Database Host and Port */}
                  <div className="grid md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="db_host" className="text-gray-700 dark:text-gray-300">
                        Database Host <span className="text-red-500">*</span>
                      </Label>
                      <div className="relative">
                        <Server className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                        <Input
                          id="db_host"
                          type="text"
                          placeholder="localhost"
                          value={data.db_host}
                          onChange={(e) => setData('db_host', e.target.value)}
                          className="pl-10 h-12"
                          required
                        />
                      </div>
                      {errors.db_host && (
                        <p className="text-sm text-red-500">{errors.db_host}</p>
                      )}
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="db_port" className="text-gray-700 dark:text-gray-300">
                        Database Port <span className="text-red-500">*</span>
                      </Label>
                      <div className="relative">
                        <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                        <Input
                          id="db_port"
                          type="text"
                          placeholder="3306"
                          value={data.db_port}
                          onChange={(e) => setData('db_port', e.target.value)}
                          className="pl-10 h-12"
                          required
                        />
                      </div>
                      {errors.db_port && (
                        <p className="text-sm text-red-500">{errors.db_port}</p>
                      )}
                    </div>
                  </div>

                  {/* Database Name */}
                  <div className="space-y-2">
                    <Label htmlFor="db_name" className="text-gray-700 dark:text-gray-300">
                      Database Name <span className="text-red-500">*</span>
                    </Label>
                    <div className="relative">
                      <Database className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <Input
                        id="db_name"
                        type="text"
                        placeholder="postuno_db"
                        value={data.db_name}
                        onChange={(e) => setData('db_name', e.target.value)}
                        className="pl-10 h-12"
                        required
                      />
                    </div>
                    {errors.db_name && (
                      <p className="text-sm text-red-500">{errors.db_name}</p>
                    )}
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Make sure this database exists on your server
                    </p>
                  </div>

                  {/* Database User */}
                  <div className="space-y-2">
                    <Label htmlFor="db_user" className="text-gray-700 dark:text-gray-300">
                      Database Username <span className="text-red-500">*</span>
                    </Label>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <Input
                        id="db_user"
                        type="text"
                        placeholder="root"
                        value={data.db_user}
                        onChange={(e) => setData('db_user', e.target.value)}
                        className="pl-10 h-12"
                        required
                      />
                    </div>
                    {errors.db_user && (
                      <p className="text-sm text-red-500">{errors.db_user}</p>
                    )}
                  </div>

                  {/* Database Password */}
                  <div className="space-y-2">
                    <Label htmlFor="db_password" className="text-gray-700 dark:text-gray-300">
                      Database Password
                    </Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <Input
                        id="db_password"
                        type="password"
                        placeholder="Enter database password"
                        value={data.db_password}
                        onChange={(e) => setData('db_password', e.target.value)}
                        className="pl-10 h-12"
                      />
                    </div>
                    {errors.db_password && (
                      <p className="text-sm text-red-500">{errors.db_password}</p>
                    )}
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Leave empty if your database has no password
                    </p>
                  </div>

                  {/* Test Connection Button */}
                  <div>
                    <Button
                      type="button"
                      onClick={handleTestConnection}
                      disabled={testingConnection || !data.db_host || !data.db_name || !data.db_user}
                      variant="outline"
                      className="w-full"
                    >
                      {testingConnection ? (
                        <span className="flex items-center justify-center">
                          <svg className="animate-spin -ml-1 mr-3 h-5 w-5" 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>
                          Testing Connection...
                        </span>
                      ) : (
                        "Test Database Connection"
                      )}
                    </Button>
                  </div>

                  {/* Connection Status */}
                  {connectionStatus === 'success' && (
                    <div className="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">
                            Connection Successful
                          </p>
                          <p className="text-green-600 dark:text-green-400 text-sm mt-1">
                            Database connection established successfully.
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {connectionStatus === 'error' && (
                    <div className="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">
                            Connection Failed
                          </p>
                          <p className="text-red-600 dark:text-red-400 text-sm mt-1">
                            {connectionError || 'Please check your database credentials and try again.'}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Error Message */}
                  {errors.general && (
                    <div className="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" />
                        <p className="text-red-600 dark:text-red-400">{errors.general}</p>
                      </div>
                    </div>
                  )}

                  {/* Action Buttons */}
                  <div className="flex gap-4 pt-4">
                    <Button
                      type="button"
                      onClick={handleBack}
                      variant="outline"
                      className="flex-1"
                      disabled={processing}
                    >
                      <ArrowLeft className="mr-2 h-4 w-4" />
                      Back
                    </Button>
                    <Button
                      type="submit"
                      disabled={processing || !data.db_host || !data.db_name || !data.db_user}
                      className="flex-1 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white"
                    >
                      {processing ? (
                        <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>
                          Setting Up Database...
                        </span>
                      ) : (
                        <span className="flex items-center justify-center">
                          Configure Database
                          <ArrowRight className="ml-2 h-4 w-4" />
                        </span>
                      )}
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    </div>
  )
}