"use client";

import { useState } from "react";
import {
  ZURICH_UNIVERSITIES,
  SEMESTERS,
  COUNTRIES,
} from "@/lib/constants";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { authClient } from "@/lib/auth-client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Spinner } from "@/components/ui/spinner";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { AlertCircle, Mail, Lock, User, Briefcase } from "lucide-react";
import { Checkbox } from "@/components/ui/checkbox";

export default function SignupPage() {
  const router = useRouter();


  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    confirmPassword: "",
    role: "EXPLORER" as "EXPLORER" | "GUIDE",
    university: ZURICH_UNIVERSITIES[0] as string,
    customUniversity: "",
    semester: SEMESTERS[0] as string,
    countryOfOrigin: COUNTRIES[0].code as string,
  });
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    // Validation
    if (formData.password !== formData.confirmPassword) {
      setError("Passwords do not match");
      return;
    }

    if (formData.password.length < 8) {
      setError("Password must be at least 8 characters long");
      return;
    }

    if (!formData.university) {
      setError("University is required");
      return;
    }
  if (formData.university === "Other - Add your university" && !formData.customUniversity) {
      setError("Please enter your university name");
      return;
    }
    if (!formData.semester) {
      setError("Semester is required");
      return;
    }
    if (!formData.countryOfOrigin) {
      setError("Country of origin is required");
      return;
    }
    if (!agreedToTerms) {
      setError("Please agree to the Terms of Service and Privacy Policy");
      return;
    }

    setIsLoading(true);

    try {
      const { data, error } = await authClient.signUp.email({
        name: formData.name,
        email: formData.email,
        password: formData.password,
        callbackURL: "/dashboard",
      });

      if (error) {
        setError(error.message || "Failed to create account");
        setIsLoading(false);
        return;
      }

      if (data) {
        // After signup, update the user role and student info
        if (formData.role === "GUIDE") {
          await fetch("/api/auth/update-role", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ role: "GUIDE" }),
          });
        }
        // Send university, semester, countryOfOrigin
        await fetch("/api/users/update-student-info", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            university: formData.university === "Other - Add your university" ? formData.customUniversity : formData.university,
            semester: formData.semester,
            countryOfOrigin: formData.countryOfOrigin,
          }),
        });

        router.push("/dashboard");
        router.refresh();
      }
    } catch {
      setError("An unexpected error occurred. Please try again.");
      setIsLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="space-y-2">
        <h1 className="text-3xl font-bold tracking-tight">Create an account</h1>
        <p className="text-gray-500">
          Join our community of travelers and guides
        </p>
      </div>

      {error && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

  <form onSubmit={handleSubmit} className="space-y-4">
        {/* University & Semester Dropdown */}
        <div className='w-full flex gap-2'>
          <div className="space-y-2 w-full">
            <Label htmlFor="university">University</Label>
            <Select
              value={formData.university}
              onValueChange={(value) => {
                setFormData({ ...formData, university: value });
                if (value !== "Other - Add your university") {
                  setFormData((prev) => ({ ...prev, customUniversity: "" }));
                }
              }}
              required
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select your university" />
              </SelectTrigger>
              <SelectContent>
                {ZURICH_UNIVERSITIES.map((uni: string) => (
                  <SelectItem key={uni} value={uni}>{uni}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            {formData.university === "Other - Add your university" && (
              <Input
                id="customUniversity"
                type="text"
                placeholder="Enter your university"
                value={formData.customUniversity}
                onChange={(e) => setFormData({ ...formData, customUniversity: e.target.value })}
                required
              />
            )}
          </div>

          {/* Semester Dropdown */}
          <div className="space-y-2 w-full">
            <Label htmlFor="semester">Semester</Label>
            <Select
              value={formData.semester}
              onValueChange={(value: string) => setFormData({ ...formData, semester: value })}
              required
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select your semester" />
              </SelectTrigger>
              <SelectContent>
                {SEMESTERS.map((sem: string) => (
                  <SelectItem key={sem} value={sem}>{sem}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

        </div>


        {/* Country of Origin & Role Dropdown */}
        <div className="flex w-full gap-2">
          <div className="space-y-2 w-full">
            <Label htmlFor="role">I want to join as</Label>
            <div className="relative">
              <Briefcase className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400 z-10" />
              <Select
                value={formData.role}
                onValueChange={(value: "EXPLORER" | "GUIDE") =>
                  setFormData({ ...formData, role: value })
                }
                required
              >
                <SelectTrigger className="pl-10 w-full">
                  <SelectValue placeholder="Select your role" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="EXPLORER">Explorer - Book tours</SelectItem>
                  <SelectItem value="GUIDE">Guide - Offer tours</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <div className="space-y-2 w-full">
            <Label htmlFor="countryOfOrigin">Country of Origin</Label>
            <Select
              value={formData.countryOfOrigin}
              onValueChange={(value: string) => setFormData({ ...formData, countryOfOrigin: value })}
              required
            >
              <SelectTrigger className="w-full">
                <SelectValue placeholder="Select your country" />
              </SelectTrigger>
              <SelectContent>
                {COUNTRIES.map((country: { code: string; name: string; flag: string }) => (
                  <SelectItem key={country.code} value={country.code}>
                    {country.flag} {country.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="name">Full name</Label>
          <div className="relative">
            <User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              id="name"
              type="text"
              placeholder="John Doe"
              value={formData.name}
              onChange={(e) =>
                setFormData({ ...formData, name: e.target.value })
              }
              required
              className="pl-10"
              disabled={isLoading}
            />
          </div>
        </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 h-4 w-4 text-gray-400" />
            <Input
              id="email"
              type="email"
              placeholder="you@example.com"
              value={formData.email}
              onChange={(e) =>
                setFormData({ ...formData, email: e.target.value })
              }
              required
              className="pl-10"
              disabled={isLoading}
            />
          </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 h-4 w-4 text-gray-400" />
            <Input
              id="password"
              type="password"
              placeholder="At least 8 characters"
              value={formData.password}
              onChange={(e) =>
                setFormData({ ...formData, password: e.target.value })
              }
              required
              minLength={8}
              className="pl-10"
              disabled={isLoading}
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label htmlFor="confirmPassword">Confirm password</Label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              id="confirmPassword"
              type="password"
              placeholder="Re-enter your password"
              value={formData.confirmPassword}
              onChange={(e) =>
                setFormData({ ...formData, confirmPassword: e.target.value })
              }
              required
              minLength={8}
              className="pl-10"
              disabled={isLoading}
            />
          </div>
        </div>

        <div className="flex items-start space-x-2">
          <Checkbox
            id="terms"
            checked={agreedToTerms}
            onCheckedChange={(checked) =>
              setAgreedToTerms(checked as boolean)
            }
            disabled={isLoading}
          />
          <label
            htmlFor="terms"
            className="text-sm text-gray-600 leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
          >
            I agree to the{" "}
            <Link href="/terms" className="text-blue-600 hover:underline">
              Terms of Service
            </Link>{" "}
            and{" "}
            <Link href="/privacy" className="text-blue-600 hover:underline">
              Privacy Policy
            </Link>
          </label>
        </div>

        <Button
          type="submit"
          className="w-full"
          size="lg"
          disabled={isLoading}
        >
          {isLoading ? (
            <>
              <Spinner className="mr-2 h-4 w-4" />
              Creating account...
            </>
          ) : (
            "Create account"
          )}
        </Button>
      </form>

      <div className="relative">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-gray-200" />
        </div>
        <div className="relative flex justify-center text-sm">
          <span className="bg-white px-4 text-gray-500">
            Already have an account?
          </span>
        </div>
      </div>

      <div className="text-center">
        <Link href="/login">
          <Button variant="outline" className="w-full" size="lg">
            Sign in instead
          </Button>
        </Link>
      </div>
    </div>
  );
}
