import { useState } from 'react';
import SupportDialog from '@/components/SupportDialog';
import { LifeBuoy } from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { useAuth } from '@/hooks/useAuth';
import { lovable } from '@/integrations/lovable/index';
import { toast } from 'sonner';
import { DollarSign, BarChart3, HeartHandshake, ArrowRight } from 'lucide-react';
import heroImage from '@/assets/hero-restoration.webp';
import bpLogo from '@/assets/bp-logo.webp';

const VALUE_PROPS = [
  {
    icon: DollarSign,
    title: 'Fast Payouts',
    desc: '$200 for a scheduled meeting, $500 total if we win the job.',
  },
  {
    icon: BarChart3,
    title: 'Instant Tracking',
    desc: 'Real-time updates on every lead you send.',
  },
  {
    icon: HeartHandshake,
    title: 'Elite Support',
    desc: 'We treat your customers like our own.',
  },
];

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);
  const { signIn } = useAuth();
  const navigate = useNavigate();
  const [supportOpen, setSupportOpen] = useState(false);

  const handleGoogleSignIn = async () => {
    setGoogleLoading(true);
    try {
      const result = await lovable.auth.signInWithOAuth('google', {
        redirect_uri: window.location.origin,
      });
      if (result.error) {
        toast.error('Google sign-in failed');
        return;
      }
      if (result.redirected) return;
      navigate('/');
    } catch (err: any) {
      toast.error(err.message || 'Google sign-in failed');
    } finally {
      setGoogleLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      await signIn(email, password);
      navigate('/');
    } catch (err: any) {
      toast.error(err.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="relative min-h-[100dvh]">
      {/* Hero background */}
      <div className="absolute inset-0">
        <img
          src={heroImage}
          alt="Professional restoration project"
          className="h-full w-full object-cover"
          width={1920}
          height={1080}
          fetchPriority="high"
          decoding="sync"
        />
        <div className="absolute inset-0 bg-gradient-to-b from-primary/90 via-primary/80 to-primary/95" />
      </div>

      {/* Content */}
      <div className="relative z-10 flex min-h-[100dvh] flex-col items-center justify-start px-4 py-8 pb-[calc(2rem+env(safe-area-inset-bottom))] md:py-12">
        {/* Logo */}
        <img
          src={bpLogo}
          alt="BP Restoration"
          className="mb-6 h-16 w-auto max-w-[280px] rounded-2xl bg-primary-foreground/95 px-4 py-2 shadow-lg md:h-20 md:max-w-[340px]"
          width={702}
          height={168}
          decoding="async"
        />

        {/* Headline */}
        <h1 className="mb-2 text-center text-3xl font-bold text-primary-foreground md:text-4xl">
          Welcome, Partner!
        </h1>
        <p className="mx-auto mb-8 max-w-md text-center text-sm leading-relaxed text-primary-foreground/80 md:text-base">
          We value your expertise and your referrals. Use this portal to track your earnings and help us provide elite restoration services together.
        </p>

        {/* Value Props */}
        <div className="mb-8 grid w-full max-w-lg gap-3 md:grid-cols-3 md:max-w-3xl">
          {VALUE_PROPS.map((prop) => (
            <div
              key={prop.title}
              className="flex items-start gap-3 rounded-xl bg-primary-foreground/15 p-4 md:flex-col md:items-center md:text-center"
            >
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-accent text-accent-foreground">
                <prop.icon className="h-5 w-5" />
              </div>
              <div>
                <h2 className="text-sm font-semibold text-primary-foreground">{prop.title}</h2>
                <p className="text-xs text-primary-foreground/70">{prop.desc}</p>
              </div>
            </div>
          ))}
        </div>

        {/* Sign-In Card */}
        <Card className="w-full max-w-sm border-0 shadow-2xl">
          <CardContent className="p-6">
            <h2 className="mb-1 text-lg font-bold text-foreground">Partner Sign-In</h2>
            <p className="mb-5 text-xs text-muted-foreground">
              Access your referral dashboard
            </p>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-1.5">
                <Label htmlFor="email" className="text-xs">Email</Label>
                <Input
                  id="email"
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@example.com"
                  className="h-12 text-base"
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="password" className="text-xs">Password</Label>
                <Input
                  id="password"
                  type="password"
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••"
                  className="h-12 text-base"
                />
              </div>
              <Button type="submit" className="w-full h-12 text-base font-semibold" disabled={loading}>
                {loading ? 'Signing in...' : 'Sign In'}
              </Button>
            </form>
            <div className="mt-5 flex flex-col items-center gap-3">
              <div className="relative w-full">
                <div className="absolute inset-0 flex items-center"><div className="h-px w-full bg-border" /></div>
                <div className="relative flex justify-center text-xs"><span className="bg-card px-2 text-muted-foreground">or</span></div>
              </div>
              <Button
                type="button"
                variant="outline"
                className="w-full h-12 gap-2 text-base font-medium"
                onClick={handleGoogleSignIn}
                disabled={googleLoading}
              >
                <svg className="h-5 w-5" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
                {googleLoading ? 'Signing in...' : 'Sign in with Google'}
              </Button>
              <div className="h-px w-full bg-border" />
              <Link to="/signup">
                <Button variant="outline" className="h-12 gap-2 px-6 font-extrabold text-primary">
                  Join the Program <ArrowRight className="h-4 w-4" />
                </Button>
              </Link>
            </div>
          </CardContent>
        </Card>

        {/* Footer quote */}
        <p className="mx-auto mt-8 max-w-sm text-center text-xs italic text-primary-foreground/60">
          "Welcome to the Team! We value your expertise and your referrals. Use this portal to track your earnings and help us provide elite restoration services together."
        </p>

        {/* Support FAB */}
        <button
          onClick={() => setSupportOpen(true)}
          className="fixed bottom-[calc(1.5rem+env(safe-area-inset-bottom))] left-6 z-50 flex h-12 w-12 items-center justify-center rounded-full bg-primary/80 shadow-lg transition-transform hover:scale-105 active:scale-95"
          aria-label="Contact Support"
        >
          <LifeBuoy className="h-5 w-5 text-primary-foreground" />
        </button>
        <SupportDialog open={supportOpen} onOpenChange={setSupportOpen} />
      </div>
    </div>
  );
}
