import { useState, useEffect } from "react";
import acmLogoFull from "@/assets/acm-logo-full.png";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
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 { useToast } from "@/hooks/use-toast";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { ArrowLeft, CheckCircle2, User } from "lucide-react";
import type { Enums } from "@/integrations/supabase/types";

function getRoleBasedPath(role: Enums<"app_role"> | null): string {
  switch (role) {
    case "admin":
    case "manager":
      return "/dashboard";
    case "legal":
      return "/legal";
    case "master_board_member":
      return "/master-board";
    case "arc_member":
      return "/arc";
    case "association_management":
    case "rv_boat_lot" as Enums<"app_role">:
    case "homeowner":
    case "board_member":
    case "fining_member":
      return "/homeowner";
    default:
      return "/dashboard";
  }
}

interface MatchedOwner {
  id: string;
  first_name: string;
  last_name: string;
  email: string | null;
}

type SignupStep = "credentials" | "select-owner" | "success";

export default function Auth() {
  const [isLogin, setIsLogin] = useState(true);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [lastName, setLastName] = useState("");
  const [unitNumber, setUnitNumber] = useState("");
  const [accountNumber, setAccountNumber] = useState("");
  const [loading, setLoading] = useState(false);
  const [resetLoading, setResetLoading] = useState(false);
  const [signupStep, setSignupStep] = useState<SignupStep>("credentials");
  const [matchedOwners, setMatchedOwners] = useState<MatchedOwner[]>([]);
  const [selectedOwnerId, setSelectedOwnerId] = useState("");
  const navigate = useNavigate();
  const { toast } = useToast();

  useEffect(() => {
    const loadSession = async () => {
      const {
        data: { session },
        error,
      } = await supabase.auth.getSession();
      if (error) {
        if (error.code === "refresh_token_not_found" || error.message?.includes("Invalid Refresh Token")) {
          await supabase.auth.signOut({ scope: "local" });
        }
        return;
      }
      if (session) {
        const blocked = await enforceMaintenanceMode(session.user.id);
        if (blocked) return;
        await redirectByRole(session.user.id);
      }
    };
    void loadSession();
  }, []);

  // Returns true if the user was signed out due to maintenance mode.
  const enforceMaintenanceMode = async (userId: string): Promise<boolean> => {
    try {
      const [{ data: status }, { data: rolesData }] = await Promise.all([
        supabase.rpc("get_maintenance_status"),
        supabase.from("user_roles").select("role").eq("user_id", userId),
      ]);
      const enabled = (status as any)?.enabled === true;
      if (!enabled) return false;
      const isAdmin = (rolesData || []).some((r: any) => r.role === "admin");
      if (isAdmin) return false;
      const message =
        (status as any)?.message ||
        "The site is currently undergoing maintenance. Only administrators can sign in at this time.";
      await supabase.auth.signOut();
      toast({ title: "Maintenance mode", description: message, variant: "destructive" });
      return true;
    } catch {
      return false;
    }
  };

  const redirectByRole = async (userId: string) => {
    const { data } = await supabase.from("user_roles").select("role").eq("user_id", userId);
    const roles = (data || []).map((r) => r.role);
    // Priority: staff > legal > master_board_member > board_member/homeowner
    const priority: Enums<"app_role">[] = [
      "admin", "manager", "legal", "master_board_member",
      "board_member", "homeowner", "rv_boat_lot" as Enums<"app_role">, "fining_member", "arc_member", "staff", "employee", "association_management",
    ];
    const chosen = priority.find((r) => roles.includes(r)) ?? roles[0] ?? null;
    navigate(getRoleBasedPath(chosen));
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      let loginEmail = email.trim();
      // If the input doesn't look like an email, treat it as a username and resolve to email
      if (!loginEmail.includes("@")) {
        const { data: resolved, error: lookupErr } = await supabase
          .rpc("lookup_email_by_username", { _username: loginEmail });
        if (lookupErr) throw lookupErr;
        if (!resolved) throw new Error("No account found for that username");
        loginEmail = resolved as unknown as string;
      }
      const { data, error } = await supabase.auth.signInWithPassword({ email: loginEmail, password });
      if (error) throw error;
      if (data.user) {
        const blocked = await enforceMaintenanceMode(data.user.id);
        if (blocked) return;
        await redirectByRole(data.user.id);
      }
    } catch (error: any) {
      toast({ title: "Error", description: error.message, variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordReset = async () => {
    const targetEmail = email.trim().toLowerCase();
    if (!targetEmail) {
      toast({ title: "Email required", description: "Enter your email address first.", variant: "destructive" });
      return;
    }

    setResetLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("homeowner-signup", {
        body: { action: "request_password_reset", email: targetEmail, origin: window.location.origin },
      });
      if (error) throw error;
      if (data?.error) throw new Error(data.error);

      toast({ title: "Check your email", description: "If your email matches an owner account, a reset link has been sent." });
    } catch (error: any) {
      toast({ title: "Reset email failed", description: error.message, variant: "destructive" });
    } finally {
      setResetLoading(false);
    }
  };

  const handleValidate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!unitNumber.trim() && !accountNumber.trim()) {
      toast({
        title: "Property verification required",
        description: "Enter either your Unit ID or account number.",
        variant: "destructive",
      });
      return;
    }
    setLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("homeowner-signup", {
        body: {
          action: "submit_request",
          last_name: lastName,
          email,
          unit_identifier: unitNumber,
          account_number: accountNumber,
        },
      });
      if (error) throw error;
      if (data?.error) throw new Error(data.error);

      setSignupStep("success");
    } catch (error: any) {
      toast({ title: "Registration request failed", description: error.message, variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async () => {
    if (!selectedOwnerId) {
      toast({ title: "Select an owner", description: "Please choose which owner you are.", variant: "destructive" });
      return;
    }
    setLoading(true);
    try {
      const { data, error } = await supabase.functions.invoke("homeowner-signup", {
        body: { action: "register", email, password, owner_id: selectedOwnerId },
      });
      if (error) throw error;
      if (data?.error) throw new Error(data.error);

      setSignupStep("success");

      // Auto sign-in
      setTimeout(async () => {
        const { error: signInErr } = await supabase.auth.signInWithPassword({ email, password });
        if (!signInErr) {
          navigate("/homeowner");
        }
      }, 1500);
    } catch (error: any) {
      toast({ title: "Registration Failed", description: error.message, variant: "destructive" });
    } finally {
      setLoading(false);
    }
  };

  const resetSignup = () => {
    setSignupStep("credentials");
    setMatchedOwners([]);
    setSelectedOwnerId("");
  };

  // Login form
  if (isLogin) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img
          src="https://yqdefzjapnzabowsgoyd.supabase.co/storage/v1/object/public/company-assets/media/2752446c-468b-4afc-91b4-e6108ba32a0b.png"
          alt="Avria Community Management"
          width="120"
        />
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <CardTitle>Sign In</CardTitle>
            <CardDescription>Welcome back to ACM</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="email">Email or Username</Label>
                <Input
                  id="email"
                  type="text"
                  autoComplete="username"
                  placeholder="you@example.com or your username"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="password">Password</Label>
                <Input
                  id="password"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
              </div>
              <Button type="submit" className="w-full" disabled={loading}>
                {loading ? "Signing in..." : "Sign In"}
              </Button>
            </form>
            <div className="mt-3 text-center text-sm">
              <button
                type="button"
                onClick={handlePasswordReset}
                disabled={resetLoading}
                className="font-medium text-primary hover:underline disabled:pointer-events-none disabled:opacity-60"
              >
                {resetLoading ? "Sending reset email..." : "Reset Password"}
              </button>
            </div>
            <div className="mt-4 text-center text-sm text-muted-foreground">
              Don't have an account?{" "}
              <button
                type="button"
                onClick={() => {
                  setIsLogin(false);
                  resetSignup();
                }}
                className="font-medium text-primary hover:underline"
              >
                Sign up
              </button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Signup - Step: Success
  if (signupStep === "success") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
        <Card className="w-full max-w-md">
          <CardContent className="flex flex-col items-center gap-4 pt-8 pb-8">
            <CheckCircle2 className="h-16 w-16 text-green-500" />
            <h2 className="text-xl font-semibold">Request submitted</h2>
            <p className="text-sm text-muted-foreground text-center">
              Your registration request has been sent for admin approval. You’ll receive an email when your account is
              approved.
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Signup - Step: Select Owner
  if (signupStep === "select-owner") {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
        <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
        <Card className="w-full max-w-md">
          <CardHeader className="text-center">
            <CardTitle>Select Your Profile</CardTitle>
            <CardDescription>Choose which owner you are for this unit</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <RadioGroup value={selectedOwnerId} onValueChange={setSelectedOwnerId} className="space-y-3">
              {matchedOwners.map((owner) => (
                <label
                  key={owner.id}
                  htmlFor={owner.id}
                  className={`flex items-center gap-3 rounded-lg border p-4 cursor-pointer transition-colors ${
                    selectedOwnerId === owner.id ? "border-primary bg-primary/5" : "border-border hover:bg-muted/50"
                  }`}
                >
                  <RadioGroupItem value={owner.id} id={owner.id} />
                  <User className="h-5 w-5 text-muted-foreground shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium">
                      {owner.first_name} {owner.last_name}
                    </p>
                    {owner.email && <p className="text-sm text-muted-foreground truncate">{owner.email}</p>}
                  </div>
                </label>
              ))}
            </RadioGroup>

            <div className="flex gap-2 pt-2">
              <Button variant="outline" onClick={resetSignup} className="flex-1">
                <ArrowLeft className="mr-2 h-4 w-4" /> Back
              </Button>
              <Button onClick={handleRegister} disabled={!selectedOwnerId || loading} className="flex-1">
                {loading ? "Creating account..." : "Create Account"}
              </Button>
            </div>

            <div className="text-center text-sm text-muted-foreground">
              Already have an account?{" "}
              <button
                type="button"
                onClick={() => setIsLogin(true)}
                className="font-medium text-primary hover:underline"
              >
                Sign in
              </button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Signup - Step: Credentials + Unit Verification
  return (
    <div className="flex min-h-screen flex-col items-center justify-center bg-secondary p-4">
      <img src={acmLogoFull} alt="Avria Community Management" className="mb-6 h-16 w-auto" />
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <CardTitle>Request Account Access</CardTitle>
          <CardDescription>Enter your details so an admin can approve your account</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleValidate} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="signup-email">Email</Label>
              <Input
                id="signup-email"
                type="email"
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="signup-last-name">Last Name</Label>
              <Input
                id="signup-last-name"
                type="text"
                placeholder="Owner last name"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                required
              />
            </div>
            <div className="border-t pt-4 mt-2">
              <p className="text-sm font-medium mb-3 text-muted-foreground">
                Property Verification — enter Unit ID or account number
              </p>
              <div className="space-y-3">
                <div className="space-y-2">
                  <Label htmlFor="unit-number">Unit ID</Label>
                  <Input
                    id="unit-number"
                    type="text"
                    placeholder="e.g. 101, A-204"
                    value={unitNumber}
                    onChange={(e) => setUnitNumber(e.target.value)}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="account-number">Account Number</Label>
                  <Input
                    id="account-number"
                    type="text"
                    placeholder="Your account number"
                    value={accountNumber}
                    onChange={(e) => setAccountNumber(e.target.value)}
                  />
                </div>
              </div>
            </div>
            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Submitting..." : "Submit for Approval"}
            </Button>
          </form>
          <div className="mt-4 text-center text-sm text-muted-foreground">
            Already have an account?{" "}
            <button type="button" onClick={() => setIsLogin(true)} className="font-medium text-primary hover:underline">
              Sign in
            </button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
