import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Footer } from "./Footer";
import { 
  User, 
  Lock,
  Eye,
  EyeOff,
  ArrowRight,
  Sparkles
} from "lucide-react";
import { useData } from "./contexts/DataContext";

interface LoginPageProps {
  onNavigateToSignup: () => void;
  onNavigateToLanding: () => void;
  onLoginComplete: (userData: any) => void;
}

export function LoginPage({ onNavigateToSignup, onNavigateToLanding, onLoginComplete }: LoginPageProps) {
  const { users, updateUser } = useData();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");

  const handleLogin = () => {
    setError("");
    
    if (!username || !password) {
      setError("사용자명과 비밀번호를 입력해주세요");
      return;
    }

    // DataContext에서 사용자 찾기
    const user = users.find(u => u.username === username && u.password === password);
    
    if (user) {
      if (!user.isActive) {
        setError("비활성화된 계정입니다. 관리자에게 문의하세요.");
        return;
      }

      // 마지막 로그인 시간 업데이트
      updateUser(user.id, { lastLogin: new Date().toISOString() });

      onLoginComplete({
        email: user.email,
        role: user.role,
        name: user.name,
        companyName: user.companyName,
        position: user.position,
        userId: user.id,
      });
    } else {
      setError("사용자명 또는 비밀번호가 올바르지 않습니다");
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleLogin();
    }
  };

  return (
    <div className="min-h-screen bg-background flex flex-col items-center justify-center px-6 py-12 relative">
      {/* Logo and Title Section */}
      <div className="text-center mb-10">
        <div className="flex items-center justify-center gap-4 mb-6">
          <div className="w-14 h-14 rounded-2xl flex items-center justify-center shadow-lg relative overflow-hidden bg-primary hover:scale-110 transition-transform">
            <div className="text-primary-foreground font-bold text-2xl">S</div>
            <div className="absolute inset-0 bg-gradient-to-br from-white/20 to-transparent"></div>
          </div>
          <div className="text-left">
            <h1 className="text-4xl text-foreground tracking-tight">SAM</h1>
            <p className="text-sm text-muted-foreground">Smart Automation Management</p>
          </div>
        </div>
        <h2 className="mb-3 text-foreground">
          통합 생산 관리 시스템
        </h2>
        <p className="text-muted-foreground flex items-center justify-center gap-2">
          <Sparkles className="w-4 h-4 text-primary" />
          <span>로그인하여 스마트 팩토리를 경험하세요</span>
        </p>
      </div>

      {/* Login Card */}
      <div className="w-full max-w-md bg-card border border-border rounded-2xl shadow-xl p-8 space-y-6">
        <div className="text-center">
          <h3 className="text-foreground mb-1">로그인</h3>
          <p className="text-sm text-muted-foreground">계정 정보를 입력해주세요</p>
        </div>

        {error && (
          <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-3">
            <p className="text-sm text-destructive text-center">{error}</p>
          </div>
        )}

        <div className="space-y-5">
          {/* Username Field */}
          <div>
            <Label htmlFor="username" className="mb-2 block">
              사용자명
            </Label>
            <div className="relative group">
              <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground group-focus-within:text-primary transition-colors" />
              <Input
                id="username"
                type="text"
                placeholder="manager"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                onKeyPress={handleKeyPress}
                className="pl-11 h-11"
              />
            </div>
          </div>

          {/* Password Field */}
          <div>
            <Label htmlFor="password" className="mb-2 block">
              비밀번호
            </Label>
            <div className="relative group">
              <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground group-focus-within:text-primary transition-colors" />
              <Input
                id="password"
                type={showPassword ? "text" : "password"}
                placeholder="••••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onKeyPress={handleKeyPress}
                className="pl-11 pr-11 h-11"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
              >
                {showPassword ? (
                  <EyeOff className="w-5 h-5" />
                ) : (
                  <Eye className="w-5 h-5" />
                )}
              </button>
            </div>
          </div>
        </div>

        {/* Login Button */}
        <Button 
          onClick={handleLogin}
          className="w-full h-11"
        >
          로그인
          <ArrowRight className="ml-2 w-4 h-4" />
        </Button>

        {/* Divider */}
        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-border"></div>
          </div>
          <div className="relative flex justify-center text-sm">
            <span className="px-4 bg-card text-muted-foreground">또는 데모 계정으로 체험</span>
          </div>
        </div>

        {/* Demo Account Buttons */}
        <div className="space-y-2">
          {[
            { username: "ceo", password: "ceo123", label: "김대표", sublabel: "대표이사", color: "purple" },
            { username: "manager", password: "manager123", label: "박관리", sublabel: "생산관리자", color: "blue" },
            { username: "worker", password: "worker123", label: "이생산", sublabel: "생산직", color: "green" }
          ].map((account) => (
            <button
              key={account.username}
              onClick={() => {
                setUsername(account.username);
                setPassword(account.password);
                setError("");
              }}
              className="w-full p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent transition-all text-left group"
            >
              <div className="flex items-center gap-3">
                <div 
                  className={`w-11 h-11 rounded-lg flex items-center justify-center text-primary-foreground bg-primary shadow-sm group-hover:scale-110 transition-transform`}
                >
                  <User className="w-5 h-5" />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="font-semibold text-foreground">{account.label}</span>
                    <span className="text-xs text-muted-foreground bg-muted px-2 py-0.5 rounded-full">{account.sublabel}</span>
                  </div>
                  <div className="text-xs text-muted-foreground mt-0.5">
                    {account.username} / {account.password}
                  </div>
                </div>
                <ArrowRight className="w-4 h-4 text-muted-foreground group-hover:text-primary group-hover:translate-x-1 transition-all" />
              </div>
            </button>
          ))}
        </div>

        {/* Helper Text */}
        <div className="bg-primary/10 border border-primary/20 rounded-lg p-3">
          <p className="text-center text-xs text-foreground">
            💡 데모 버전입니다. 위의 계정을 클릭하여 바로 체험해보세요.
          </p>
        </div>

        {/* Divider */}
        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-border"></div>
          </div>
        </div>

        {/* Signup Link */}
        <div className="text-center">
          <p className="text-sm text-muted-foreground">
            아직 계정이 없으신가요?{" "}
            <button 
              onClick={onNavigateToSignup}
              className="text-primary font-semibold hover:underline transition-colors"
            >
              회원가입
            </button>
          </p>
        </div>
      </div>

      {/* Back to Landing Link */}
      <div className="mt-8">
        <button 
          onClick={onNavigateToLanding}
          className="text-sm text-muted-foreground hover:text-foreground transition-colors flex items-center gap-2 hover:gap-3"
        >
          <ArrowRight className="w-4 h-4 rotate-180" />
          랜딩페이지로 돌아가기
        </button>
      </div>

      {/* Footer */}
      <Footer />
    </div>
  );
}