"use client";

import { useState, useRef } from "react";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Building2, Upload, X } from "lucide-react";
import { useCreateOrganization } from "../hooks/organization.hook";
import { capitalizeFirstLetter } from "@/lib/capitalize";

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

  const { mutate, isPending } = useCreateOrganization(() => {
    setName("");
    setGstin("");
    setLogo(null);
    setPreview(null);
  });

  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();

    mutate({
      name: capitalizeFirstLetter(name.trim()),
      gstin,
      logo: logo ?? undefined,
    });
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-3xl font-extrabold tracking-tight text-foreground">
          Create Organization
        </h2>
        <p className="text-muted-foreground text-sm mt-1">
          Register a new organization on the platform
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-2 border-border bg-card shadow-sm">
          <CardHeader className="border-b border-border">
            <CardTitle className="text-card-foreground text-base font-bold flex items-center gap-2">
              <Building2 className="h-4 w-4 text-primary" /> Organization
              Details
            </CardTitle>
            <CardDescription className="text-muted-foreground text-xs">
              Fill in the required information to register the organization
            </CardDescription>
          </CardHeader>
          <CardContent className="p-6">
            <form onSubmit={handleSubmit} className="space-y-5">
              <div className="space-y-1.5">
                <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                  Organization Name <span className="text-destructive">*</span>
                </Label>
                <Input
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="e.g. Apex Security Services"
                  required
                  className="h-9 text-sm bg-background border-border focus-visible:ring-primary"
                />
              </div>

              <div className="space-y-1.5">
                <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                  Goods and Services Tax Identification Number{" "}
                  <span className="text-destructive">*</span>
                </Label>
                <Input
                  value={gstin}
                  onChange={(e) => setGstin(e.target.value.toUpperCase())}
                  placeholder="e.g. 22AAAAA0000A1Z5"
                  required
                  maxLength={15}
                  className="h-9 text-sm font-mono bg-background border-border focus-visible:ring-primary"
                />
              </div>

              <div className="space-y-1.5">
                <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                  Logo (Optional)
                </Label>
                <div
                  onClick={() => fileRef.current?.click()}
                  className="border-2 border-dashed border-border rounded-lg p-6 flex flex-col items-center justify-center gap-2 cursor-pointer hover:border-primary/50 transition-colors"
                >
                  {preview ? (
                    <div className="relative">
                      <img
                        src={preview}
                        alt="logo preview"
                        className="h-16 w-16 object-contain rounded-lg"
                      />
                      <button
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          setLogo(null);
                          setPreview(null);
                        }}
                        className="absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-0.5"
                      >
                        <X className="h-3 w-3" />
                      </button>
                    </div>
                  ) : (
                    <>
                      <Upload className="h-6 w-6 text-muted-foreground" />
                      <p className="text-xs text-muted-foreground">
                        Click to upload logo
                      </p>
                      <p className="text-[11px] text-muted-foreground/60">
                        PNG, JPG up to 2MB
                      </p>
                    </>
                  )}
                </div>
                <input
                  ref={fileRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={handleLogoChange}
                />
              </div>

              <div className="flex justify-end pt-2">
                <Button
                  type="submit"
                  disabled={isPending}
                  className="bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-xs h-9 px-6 shadow-sm"
                >
                  {isPending ? "Creating..." : "Create Organization"}
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>

        <Card className="border-border bg-card shadow-sm h-fit">
          <CardHeader className="border-b border-border">
            <CardTitle className="text-card-foreground text-base font-bold">
              Guidelines
            </CardTitle>
            <CardDescription className="text-muted-foreground text-xs">
              Important information before registering
            </CardDescription>
          </CardHeader>
          <CardContent className="p-6 space-y-3">
            <div className="flex items-start gap-2 border-b border-border pb-3 text-xs">
              <span className="text-primary font-bold mt-0.5">01</span>
              <p className="text-muted-foreground">
                Organization name must be unique and match official records.
              </p>
            </div>
            <div className="flex items-start gap-2 border-b border-border pb-3 text-xs">
              <span className="text-primary font-bold mt-0.5">02</span>
              <p className="text-muted-foreground">
                GSTIN must be a valid 15-character alphanumeric code.
              </p>
            </div>
            <div className="flex items-start gap-2 text-xs">
              <span className="text-primary font-bold mt-0.5">03</span>
              <p className="text-muted-foreground">
                Logo should be a clear image in PNG or JPG format, max 2MB.
              </p>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
