import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Lock, User, Mail, Phone, Globe, Building, Text } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { userSchema, UserFormValues } from "./outgoing/formSchema";
import { useRegisterExternalPortalUser } from "../hooks/useRegisterExternalPortalUser";
import { useTenantConfig } from "@/layout/components/TenantConfig";

const Signup = () => {
  const navigate = useNavigate();
  const { config: tenantConfig } = useTenantConfig();
  const { registerExternalPortalUser, isRegistering } =
    useRegisterExternalPortalUser();

  const form = useForm<UserFormValues>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      email: "",
      username: "",
      phoneNumber: "",
      userType: "external_organization",
      name: {
        am: "",
        en: "",
      },
    },
    mode: "onChange",
  });

  const onSubmit = async (values: UserFormValues) => {
    try {
      await registerExternalPortalUser(values);
      const params = new URLSearchParams();
      if (values.email) params.set("email", values.email.trim());
      if (values.phoneNumber) {
        const normalizedPhone = values.phoneNumber.trim().replace(/^0/, "+251");
        params.set("phone", normalizedPhone);
      }
      navigate(`/external-portal/verify-otp?${params.toString()}`);
    } catch (error) {
      console.error("Signup error:", error);
      
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center p-4">
      <div className="w-full max-w-6xl bg-white rounded-2xl shadow-xl overflow-hidden flex flex-col md:flex-row h-full max-h-[800px]">
        {/* Left Panel */}
        <div className="md:w-1/2 w-full p-8 md:p-12 flex flex-col">
          <div className="flex items-center mb-8">
            <img
              src={tenantConfig.logo || "/assets/smart-office-logo.svg"}
              alt={tenantConfig.appName}
              className="h-10 object-contain"
            />
            <span className="ml-2 text-xl font-semibold text-gray-800">
              {tenantConfig.appName}
            </span>
          </div>

          <div className="mb-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-2">
              Create Organization Account
            </h1>
            <p className="text-gray-500">
              Streamline your workflow with our paperless solution
            </p>
          </div>

          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="space-y-6 flex-1 flex flex-col"
          >
            <div className="space-y-4">
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="email"
                  placeholder="Organization Email"
                  className="h-12 rounded-lg border-gray-300 pl-10 text-base focus-visible:ring-2 focus-visible:ring-primary"
                  {...form.register("email")}
                />
              </div>

              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="text"
                  placeholder="Organization Username"
                  className="h-12 rounded-lg border-gray-300 pl-10 text-base focus-visible:ring-2 focus-visible:ring-primary"
                  {...form.register("username")}
                />
              </div>

              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="tel"
                  placeholder="Organization Phone Number"
                  className="h-12 rounded-lg border-gray-300 pl-10 text-base focus-visible:ring-2 focus-visible:ring-primary"
                  {...form.register("phoneNumber")}
                />
              </div>

              <div className="relative">
                <Text className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="text"
                  placeholder="Organization Name (English)"
                  className="h-12 rounded-lg border-gray-300 pl-10 text-base focus-visible:ring-2 focus-visible:ring-primary"
                  {...form.register("name.en")}
                />
              </div>

              <div className="relative">
                <Text className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <Input
                  type="text"
                  placeholder="Organization Name (Amharic)"
                  className="h-12 rounded-lg border-gray-300 pl-10 text-base focus-visible:ring-2 focus-visible:ring-primary"
                  {...form.register("name.am")}
                />
              </div>
            </div>

            <div className="mt-auto pt-4">
              <Button
                type="submit"
                className="w-full h-12 bg-primary hover:bg-primary-700 text-white text-base font-medium rounded-lg transition-all duration-300 shadow-md hover:shadow-lg"
                disabled={isRegistering}
              >
                {isRegistering ? (
                  <span className="flex items-center justify-center">
                    <svg
                      className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    Creating Account...
                  </span>
                ) : (
                  "Sign Up"
                )}
              </Button>

              <p className="text-center text-sm text-gray-500 mt-4">
                Already have an account?{" "}
                <a
                  href="/login"
                  className="text-primary hover:underline font-medium"
                >
                  Sign in
                </a>
              </p>
            </div>
          </form>
        </div>

        {/* Right Panel */}
        <div className="md:w-1/2 bg-gradient-to-br from-primary to-primary-300 text-white p-10 hidden md:flex flex-col">
          <div className="mb-8">
            <h2 className="text-3xl font-bold mb-4">
              Transform Your Office Experience
            </h2>
            <p className="text-lg opacity-90">
              Join thousands of organizations that have gone paperless with our
              smart solutions.
            </p>
          </div>

          <div className="relative flex-1 flex items-center justify-center">
            <div className="absolute inset-0 flex items-center justify-center">
              <div className="w-64 h-64 rounded-full bg-white/10 blur-xl"></div>
            </div>

            <div className="relative z-10 w-full max-w-md">
              <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20 shadow-xl">
                <div className="flex items-center mb-4">
                  <Building className="w-8 h-8 mr-3" />
                  <h3 className="text-xl font-semibold">
                    Organization Dashboard
                  </h3>
                </div>
                <div className="space-y-3">
                  <div className="flex items-center">
                    <div className="w-3 h-3 rounded-full bg-primary-400 mr-2"></div>
                    <span>Real-time document management</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-3 h-3 rounded-full bg-blue-400 mr-2"></div>
                    <span>Secure cloud storage</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-3 h-3 rounded-full bg-purple-400 mr-2"></div>
                    <span>Automated workflow</span>
                  </div>
                  <div className="flex items-center">
                    <div className="w-3 h-3 rounded-full bg-yellow-400 mr-2"></div>
                    <span>Multi-language support</span>
                  </div>
                </div>
              </div>

              <div className="mt-8 relative">
                <img
                  src="/assets/MainDashboard.png"
                  alt="Dashboard Preview"
                  className="w-full rounded-xl shadow-2xl border-4 border-white/20"
                />
                <div className="absolute -bottom-4 -right-4 bg-white p-2 rounded-lg shadow-lg">
                  <img
                    src="/assets/StatsCard.png"
                    alt="Stats Preview"
                    className="w-24 h-24 rounded-md"
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="mt-auto pt-6 text-center text-sm opacity-80">
            <p>Trusted by 500+ organizations worldwide</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Signup;
