"use client";

import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Building2, Trash2, Upload, X } from "lucide-react";
import { useCreateOrganization } from "@/modules/admin/organizations/hooks/organization.hook";

export default function CreateOrganizationPage() {
  const [name, setName] = useState("");
  const [gstin, setGstin] = useState("");
  const [gstinError, setGstinError] = useState("");
  const [logo, setLogo] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const router = useRouter();

  const { mutate, isPending } = useCreateOrganization(() => {
    router.replace("/admin/dashboard");
  });

  const GSTIN_REGEX = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;

  const handleGstinChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value.toUpperCase();
    setGstin(val);
    if (val.length === 15 && !GSTIN_REGEX.test(val)) {
      setGstinError("Invalid GSTIN format (e.g. 22AAAAA0000A1Z5)");
    } else {
      setGstinError("");
    }
  };

  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setLogo(file);
    setPreview(URL.createObjectURL(file));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!GSTIN_REGEX.test(gstin)) {
      setGstinError("Invalid GSTIN format (e.g. 22AAAAA0000A1Z5)");
      return;
    }
    mutate({ name, gstin, logo: logo ?? undefined });
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4 relative overflow-hidden">
      <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px] pointer-events-none" />

      <div className="w-full max-w-md relative">
        {/* Header */}
        <div className="text-center mb-5">
          <div className="mx-auto bg-primary/10 w-11 h-11 rounded-2xl flex items-center justify-center mb-3 border border-primary/20">
            <Building2 className="h-5 w-5 text-primary" />
          </div>
          <h1 className="text-xl font-bold tracking-tight text-foreground">
            Setup Your Organization
          </h1>
          <p className="text-muted-foreground text-sm mt-1">
            Almost done! Create your org to get started.
          </p>
        </div>

        <Card className="border-border bg-card shadow-xl">
          <CardHeader className="border-b border-border pb-3 pt-4 px-5">
            <CardTitle className="text-sm font-bold text-card-foreground flex items-center gap-2">
              <Building2 className="h-4 w-4 text-primary" /> Organization
              Details
            </CardTitle>
            <CardDescription className="text-xs text-muted-foreground">
              Fill in the required information below
            </CardDescription>
          </CardHeader>
          <CardContent className="px-5 py-4">
            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Org Name */}
              <div className="space-y-1">
                <Label className="text-xs font-medium text-foreground">
                  Organization Name <span className="text-destructive">*</span>
                </Label>
                <Input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="e.g. Sharma & Associates"
                  required
                  className="h-9 text-sm bg-background border-input"
                />
              </div>

              {/* GSTIN */}
              <div className="space-y-1">
                <Label className="text-xs font-medium text-foreground">
                  Goods and Services Tax Identification Number{" "}
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  value={gstin}
                  onChange={handleGstinChange}
                  placeholder="e.g. 22AAAAA0000A1Z5"
                  required
                  maxLength={15}
                  className={`h-9 text-sm font-mono bg-background border-input ${gstinError ? "border-destructive" : ""}`}
                />
                {gstinError && (
                  <p className="text-xs text-destructive">{gstinError}</p>
                )}
              </div>

              {/* Logo */}
              <div className="space-y-1">
                <Label className="text-xs font-medium text-foreground">
                  Logo (Optional)
                </Label>
                <div
                  onClick={() => !preview && fileRef.current?.click()}
                  className={`border-2 border-dashed border-border rounded-lg p-4 flex items-center justify-center gap-3 transition-colors ${
                    !preview ? "cursor-pointer hover:border-primary/50" : ""
                  }`}
                >
                  {preview ? (
                    <div className="flex items-center gap-3">
                      <img
                        src={preview}
                        alt="logo"
                        className="h-12 w-12 object-contain rounded-lg border border-border bg-background"
                      />
                      <div className="flex flex-col gap-1">
                        <span className="text-xs text-muted-foreground">
                          Logo selected
                        </span>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setLogo(null);
                            setPreview(null);
                          }}
                          className="flex items-center gap-1 text-xs text-destructive hover:underline w-fit"
                        >
                          <Trash2 className="h-3 w-3" />
                          Remove
                        </button>
                      </div>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 text-muted-foreground">
                      <Upload className="h-4 w-4" />
                      <span className="text-xs">
                        Click to upload · PNG, JPG up to 2MB
                      </span>
                    </div>
                  )}
                </div>
                <input
                  ref={fileRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={handleLogoChange}
                />
              </div>

              <Button
                type="submit"
                disabled={isPending}
                className="w-full h-10 bg-primary hover:bg-primary/90 text-primary-foreground font-medium shadow-sm"
              >
                {isPending ? "Creating..." : "Create Organization & Continue"}
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
