"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 {
  UserPlus,
  ArrowRight,
  ArrowLeft,
  Mail,
  Lock,
  User,
  AlertCircle,
  Eye,
  EyeOff,
  AtSign,
  CheckCircle2
} from "lucide-react"
import { motion } from "framer-motion"

export default function AccountSetup({ appName = "Postuno", errors = {}, flash = {}, old = {} }) {
  const { data, setData, post, processing } = useForm({
    name: old.name || '',
    username: old.username || '',
    email: old.email || '',
    password: '',
    password_confirmation: '',
    force: old.force || '0'
  })

  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault()

    // Use the Inertia post method directly without complex options
    post('/install/account/setup/store')
  }

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

  // Simple frontend password strength for demo (no backend validation)
  const getPasswordStrength = () => {
    if (!data.password) return { level: 0, text: '', color: '' }
    
    const password = data.password
    let level = 0
    let text = 'Weak'
    let color = 'red'
    
    if (password.length >= 6) level++
    if (password.length >= 8) level++
    if (/[A-Z]/.test(password)) level++
    if (/[0-9]/.test(password)) level++
    if (/[^A-Za-z0-9]/.test(password)) level++
    
    if (level >= 4) {
      text = 'Strong'
      color = 'green'
    } else if (level >= 3) {
      text = 'Good'
      color = 'yellow'
    } else if (level >= 2) {
      text = 'Fair'
      color = 'orange'
    }
    
    return { level, text, color }
  }

  const passwordStrength = getPasswordStrength()

  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">
              <UserPlus className="w-10 h-10 text-white" />
            </div>
            <h1 className="text-4xl font-bold text-gray-900 dark:text-white mb-4">
              Admin Account Setup
            </h1>
            <p className="text-lg text-gray-600 dark:text-gray-400">
              Create your administrator account 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 4 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: '67%' }}></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">
                  {/* Error Message Display */}
                  {flash.error && (
                    <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>
                          <h4 className="text-red-800 dark:text-red-200 font-medium">
                            Database Issue
                          </h4>
                          <p className="text-red-600 dark:text-red-300 text-sm mt-1">
                            {flash.error}
                          </p>
                          <p className="text-red-600 dark:text-red-300 text-xs mt-2">
                            Check the "Force Installation" option below to overwrite existing data.
                          </p>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Success Message Display */}
                  {flash.success && (
                    <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" />
                        <p className="text-green-600 dark:text-green-300 text-sm">
                          {flash.success}
                        </p>
                      </div>
                    </div>
                  )}

                  {/* Full Name */}
                  <div className="space-y-2">
                    <Label htmlFor="name" className="text-gray-700 dark:text-gray-300">
                      Full Name <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="name"
                        type="text"
                        placeholder="John Doe"
                        value={data.name}
                        onChange={(e) => setData('name', e.target.value)}
                        className="pl-10 h-12"
                        required
                      />
                    </div>
                    {errors.name && (
                      <p className="text-sm text-red-500">{errors.name}</p>
                    )}
                  </div>

                  {/* Username */}
                  <div className="space-y-2">
                    <Label htmlFor="username" className="text-gray-700 dark:text-gray-300">
                      Username <span className="text-red-500">*</span>
                    </Label>
                    <div className="relative">
                      <AtSign className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <Input
                        id="username"
                        type="text"
                        placeholder="admin"
                        value={data.username}
                        onChange={(e) => setData('username', e.target.value.toLowerCase().replace(/[^a-z0-9]/g, ''))}
                        className="pl-10 h-12"
                        required
                      />
                    </div>
                    {errors.username && (
                      <p className="text-sm text-red-500">{errors.username}</p>
                    )}
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Only lowercase letters and numbers allowed. This will be your login username.
                    </p>
                  </div>

                  {/* Email */}
                  <div className="space-y-2">
                    <Label htmlFor="email" className="text-gray-700 dark:text-gray-300">
                      Email Address <span className="text-red-500">*</span>
                    </Label>
                    <div className="relative">
                      <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                      <Input
                        id="email"
                        type="email"
                        placeholder="admin@example.com"
                        value={data.email}
                        onChange={(e) => setData('email', e.target.value)}
                        className="pl-10 h-12"
                        required
                      />
                    </div>
                    {errors.email && (
                      <p className="text-sm text-red-500">{errors.email}</p>
                    )}
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      You'll use this email to log in to your admin panel
                    </p>
                  </div>

                  {/* Password */}
                  <div className="space-y-2">
                    <Label htmlFor="password" className="text-gray-700 dark:text-gray-300">
                      Password <span className="text-red-500">*</span>
                    </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="password"
                        type={showPassword ? "text" : "password"}
                        placeholder="Enter a strong password"
                        value={data.password}
                        onChange={(e) => setData('password', e.target.value)}
                        className="pl-10 pr-10 h-12"
                        required
                      />
                      <button
                        type="button"
                        onClick={() => setShowPassword(!showPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2"
                      >
                        {showPassword ? (
                          <EyeOff className="w-5 h-5 text-gray-400" />
                        ) : (
                          <Eye className="w-5 h-5 text-gray-400" />
                        )}
                      </button>
                    </div>
                    {errors.password && (
                      <p className="text-sm text-red-500">{errors.password}</p>
                    )}
                    
                    {/* Password Strength Indicator */}
                    {data.password && (
                      <div className="space-y-2">
                        <div className="flex gap-1">
                          {[1, 2, 3, 4, 5].map((level) => (
                            <div
                              key={level}
                              className={`h-1 flex-1 rounded-full transition-colors ${
                                level <= passwordStrength.level
                                  ? passwordStrength.color === 'red' ? 'bg-red-500'
                                  : passwordStrength.color === 'orange' ? 'bg-orange-500'
                                  : passwordStrength.color === 'yellow' ? 'bg-yellow-500'
                                  : 'bg-green-500'
                                  : 'bg-gray-200 dark:bg-gray-700'
                              }`}
                            />
                          ))}
                        </div>
                        <p className={`text-xs ${
                          passwordStrength.color === 'red' ? 'text-red-500'
                          : passwordStrength.color === 'orange' ? 'text-orange-500'
                          : passwordStrength.color === 'yellow' ? 'text-yellow-500'
                          : 'text-green-500'
                        }`}>
                          Password Strength: {passwordStrength.text}
                        </p>
                      </div>
                    )}
                    
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      Use at least 8 characters for better security
                    </p>
                  </div>

                  {/* Confirm Password */}
                  <div className="space-y-2">
                    <Label htmlFor="password_confirmation" className="text-gray-700 dark:text-gray-300">
                      Confirm Password <span className="text-red-500">*</span>
                    </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="password_confirmation"
                        type={showConfirmPassword ? "text" : "password"}
                        placeholder="Re-enter your password"
                        value={data.password_confirmation}
                        onChange={(e) => setData('password_confirmation', e.target.value)}
                        className="pl-10 pr-10 h-12"
                        required
                      />
                      <button
                        type="button"
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        className="absolute right-3 top-1/2 transform -translate-y-1/2"
                      >
                        {showConfirmPassword ? (
                          <EyeOff className="w-5 h-5 text-gray-400" />
                        ) : (
                          <Eye className="w-5 h-5 text-gray-400" />
                        )}
                      </button>
                    </div>
                    {data.password_confirmation && data.password !== data.password_confirmation && (
                      <p className="text-sm text-red-500">Passwords do not match</p>
                    )}
                  </div>

                  {/* Info Box */}
                  <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                    <h4 className="font-medium text-blue-800 dark:text-blue-300 mb-2">
                      Admin Account Setup
                    </h4>
                    <p className="text-sm text-blue-600 dark:text-blue-400">
                      This will be your main administrator account. You can add more users later from the dashboard.
                    </p>
                  </div>

                  {/* Force Installation Option - Show always but make it more prominent when there's an error */}
                  <div className={`border rounded-lg p-4 transition-colors ${
                    flash.error
                      ? 'bg-orange-50 dark:bg-orange-900/20 border-orange-200 dark:border-orange-800'
                      : 'bg-gray-50 dark:bg-gray-900/20 border-gray-200 dark:border-gray-700'
                  }`}>
                    <div className="flex items-start space-x-3">
                      <input
                        type="checkbox"
                        id="force"
                        checked={data.force === '1'}
                        onChange={(e) => setData('force', e.target.checked ? '1' : '0')}
                        className={`w-4 h-4 rounded focus:ring-2 ${
                          flash.error
                            ? 'text-orange-600 bg-gray-100 border-gray-300 focus:ring-orange-500 dark:bg-gray-600 dark:border-gray-500'
                            : 'text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:bg-gray-600 dark:border-gray-500'
                        }`}
                      />
                      <div className="flex-1">
                        <label htmlFor="force" className={`block text-sm font-medium cursor-pointer ${
                          flash.error
                            ? 'text-orange-800 dark:text-orange-200'
                            : 'text-gray-800 dark:text-gray-200'
                        }`}>
                          Force Installation (Overwrite Existing Data)
                          {flash.error && <span className="text-red-500 ml-2">← Recommended to fix the error</span>}
                        </label>
                        <p className={`text-xs mt-1 ${
                          flash.error
                            ? 'text-orange-600 dark:text-orange-300'
                            : 'text-gray-600 dark:text-gray-400'
                        }`}>
                          {flash.error
                            ? 'This will delete all existing data in your database and create a completely fresh installation.'
                            : 'Check this option if you want to completely reset your database and start fresh. This will delete any existing data.'
                          }
                        </p>
                        {flash.error && (
                          <div className="mt-2 p-2 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded text-xs">
                            <p className="text-yellow-700 dark:text-yellow-300">
                              <strong>⚠️ Warning:</strong> Force installation will permanently delete all data in your database.
                              Make sure you have a backup if you need to preserve any existing data.
                            </p>
                          </div>
                        )}
                      </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.name || 
                        !data.email || 
                        !data.password || 
                        !data.password_confirmation ||
                        data.password !== data.password_confirmation
                      }
                      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>
                          Creating Account...
                        </span>
                      ) : (
                        <span className="flex items-center justify-center">
                          Create Admin Account
                          <ArrowRight className="ml-2 h-4 w-4" />
                        </span>
                      )}
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </motion.div>
        </div>
      </div>
    </div>
  )
}