'use client'

import { useState } from 'react'
import { useAppStore } from '@/store/app-store'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Globe, Lock, Mail, ArrowRight, Zap, Shield } from 'lucide-react'

// Demo accounts that work entirely client-side (no backend needed)
const DEMO_ACCOUNTS: Record<string, { password: string; user: { id: string; email: string; name: string; phone: string; role: string; status: string; areaId: string | null; connectionType: string } }> = {
  'admin@isp.com': {
    password: 'password123',
    user: {
      id: 'demo-admin-001',
      email: 'admin@isp.com',
      name: 'Super Admin',
      phone: '01711000000',
      role: 'SUPER_ADMIN',
      status: 'ACTIVE',
      areaId: null,
      connectionType: 'FIBER',
    },
  },
  'operator@isp.com': {
    password: 'password123',
    user: {
      id: 'demo-operator-001',
      email: 'operator@isp.com',
      name: 'System Operator',
      phone: '01812000000',
      role: 'OPERATOR',
      status: 'ACTIVE',
      areaId: null,
      connectionType: 'FIBER',
    },
  },
  'reseller@isp.com': {
    password: 'password123',
    user: {
      id: 'demo-reseller-001',
      email: 'reseller@isp.com',
      name: 'Habibur Rahman',
      phone: '01722000011',
      role: 'RESELLER',
      status: 'ACTIVE',
      areaId: null,
      connectionType: 'FIBER',
    },
  },
}

export function LoginView() {
  const { login } = useAppStore()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)

    try {
      // Try demo accounts first (client-side, instant)
      const demoAccount = DEMO_ACCOUNTS[email]
      if (demoAccount && demoAccount.password === password) {
        await new Promise((r) => setTimeout(r, 500)) // Small delay for UX
        login(demoAccount.user, `demo-${demoAccount.user.id}`)
        return
      }

      // Try API login for non-demo accounts
      try {
        const res = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email, password }),
        })
        const data = await res.json()
        if (data.success && data.data) {
          login(data.data.user, data.data.token)
        } else {
          setError(data.error || 'Invalid email or password')
        }
      } catch {
        setError('Unable to connect to server. Try a demo account below.')
      }
    } finally {
      setLoading(false)
    }
  }

  const handleDemoLogin = (role: string) => {
    const accountMap: Record<string, string> = {
      admin: 'admin@isp.com',
      operator: 'operator@isp.com',
      reseller: 'reseller@isp.com',
    }
    const selectedEmail = accountMap[role] || 'admin@isp.com'
    setEmail(selectedEmail)
    setPassword('password123')

    // Auto-login for demo accounts
    const demoAccount = DEMO_ACCOUNTS[selectedEmail]
    if (demoAccount) {
      setLoading(true)
      setTimeout(() => {
        login(demoAccount.user, `demo-${demoAccount.user.id}`)
        setLoading(false)
      }, 600)
    }
  }

  return (
    <div className="flex min-h-screen">
      {/* Left Panel - Branding */}
      <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-emerald-600 via-teal-600 to-cyan-700 relative overflow-hidden">
        <div className="absolute inset-0 opacity-10">
          <div className="absolute top-20 left-20 size-72 rounded-full bg-white blur-3xl" />
          <div className="absolute bottom-20 right-20 size-96 rounded-full bg-white blur-3xl" />
          <div className="absolute top-1/2 left-1/3 size-64 rounded-full bg-white blur-3xl" />
        </div>
        <div className="relative z-10 flex flex-col justify-center px-16 text-white">
          <div className="flex items-center gap-3 mb-8">
            <div className="flex size-14 items-center justify-center rounded-xl bg-white/20 backdrop-blur-sm">
              <Globe className="size-8 text-white" />
            </div>
            <span className="text-3xl font-bold tracking-tight">ISP Billing Pro</span>
          </div>
          <h1 className="text-4xl font-bold leading-tight mb-4">
            Enterprise ISP<br />Management Platform
          </h1>
          <p className="text-lg text-white/80 max-w-md mb-10">
            Complete billing, network management, and customer portal solution for Internet Service Providers. All currency in BDT (৳).
          </p>
          <div className="grid grid-cols-2 gap-4 max-w-md">
            {[
              { label: 'Client Management', desc: 'Full lifecycle tracking' },
              { label: 'Auto Billing', desc: 'Automated invoicing in BDT' },
              { label: 'Network Integration', desc: 'MikroTik & ONU/OLT' },
              { label: 'Real-time Monitoring', desc: 'Live session tracking' },
            ].map((feature) => (
              <div key={feature.label} className="rounded-lg bg-white/10 backdrop-blur-sm p-4">
                <h3 className="font-semibold text-sm">{feature.label}</h3>
                <p className="text-xs text-white/70 mt-1">{feature.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Right Panel - Login Form */}
      <div className="flex flex-1 items-center justify-center p-6 bg-background">
        <div className="w-full max-w-md space-y-8">
          <div className="lg:hidden flex items-center gap-3 justify-center mb-4">
            <div className="flex size-10 items-center justify-center rounded-lg bg-primary text-primary-foreground">
              <Globe className="size-6" />
            </div>
            <span className="text-2xl font-bold tracking-tight">ISP Billing Pro</span>
          </div>

          <div className="text-center lg:text-left">
            <h2 className="text-2xl font-bold tracking-tight">Welcome back</h2>
            <p className="text-muted-foreground mt-2">Sign in to your management dashboard</p>
          </div>

          {/* Quick Demo Login Buttons */}
          <div className="rounded-xl border bg-muted/50 p-4 space-y-3">
            <div className="flex items-center gap-2 text-sm font-medium">
              <Shield className="size-4 text-primary" />
              Quick Demo Access
            </div>
            <div className="grid grid-cols-3 gap-2">
              <Button
                variant="default"
                size="sm"
                className="text-xs"
                onClick={() => handleDemoLogin('admin')}
                disabled={loading}
              >
                <Zap className="size-3 mr-1" />
                Super Admin
              </Button>
              <Button
                variant="secondary"
                size="sm"
                className="text-xs"
                onClick={() => handleDemoLogin('operator')}
                disabled={loading}
              >
                <Zap className="size-3 mr-1" />
                Operator
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="text-xs"
                onClick={() => handleDemoLogin('reseller')}
                disabled={loading}
              >
                <Zap className="size-3 mr-1" />
                Reseller
              </Button>
            </div>
          </div>

          <Card className="border-0 shadow-lg">
            <CardHeader className="pb-4">
              <CardTitle className="text-lg">Sign In</CardTitle>
              <CardDescription>Enter your credentials to access the dashboard</CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleLogin} className="space-y-4">
                {error && (
                  <div className="rounded-lg bg-destructive/10 border border-destructive/20 p-3 text-sm text-destructive">
                    {error}
                  </div>
                )}
                <div className="space-y-2">
                  <Label htmlFor="email">Email Address</Label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                    <Input
                      id="email"
                      type="email"
                      placeholder="admin@isp.com"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="password">Password</Label>
                  <div className="relative">
                    <Lock className="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
                    <Input
                      id="password"
                      type="password"
                      placeholder="Enter your password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="pl-10"
                      required
                    />
                  </div>
                </div>
                <Button type="submit" className="w-full" disabled={loading}>
                  {loading ? (
                    <div className="flex items-center gap-2">
                      <div className="size-4 animate-spin rounded-full border-2 border-primary-foreground border-t-transparent" />
                      Signing in...
                    </div>
                  ) : (
                    <div className="flex items-center gap-2">
                      Sign In
                      <ArrowRight className="size-4" />
                    </div>
                  )}
                </Button>
              </form>

              <div className="mt-4">
                <Button variant="outline" className="w-full" onClick={() => handleDemoLogin('admin')} disabled={loading}>
                  <Zap className="size-4 mr-2" />
                  Quick Login as Super Admin
                </Button>
              </div>

              <div className="mt-4 rounded-lg bg-muted p-3 text-xs text-muted-foreground space-y-1">
                <p className="font-medium text-foreground">Demo Credentials:</p>
                <p>Admin: admin@isp.com / password123</p>
                <p>Operator: operator@isp.com / password123</p>
                <p>Reseller: reseller@isp.com / password123</p>
              </div>
            </CardContent>
          </Card>

          <p className="text-center text-xs text-muted-foreground">
            ISP Billing Pro v1.0 &mdash; Enterprise ISP Management &mdash; Currency: BDT (৳)
          </p>
        </div>
      </div>
    </div>
  )
}
