"use client";

import { useState, useRef, useEffect } from "react";
import { Card, CardContent, 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 {
  useGetOrganization,
  useUpdateOrganization,
} from "../hooks/organization.hook";
import { capitalizeFirstLetter } from "@/lib/capitalize";

export function UpdateOrganization() {
  const { data: org, isLoading } = useGetOrganization();

  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 GSTIN_REGEX = /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/;

  useEffect(() => {
    if (org) {
      setName(org.name ?? "");
      setGstin(org.gstin ?? "");
      if (org.logoUrl) setPreview(org.logoUrl);
    }
  }, [org]);

  const { mutate, isPending } = useUpdateOrganization();

  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: capitalizeFirstLetter(name.trim()),
      gstin: gstin.trim(),
      ...(logo && { logo }),
    });
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12 text-sm text-muted-foreground">
        Loading organization...
      </div>
    );
  }

  return (
    <Card className="border-border bg-card shadow-sm w-full">
      <CardHeader className="border-b border-border">
        <CardTitle className="text-base font-bold flex items-center gap-2">
          <Building2 className="h-4 w-4 text-primary" /> Organization Details
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-5">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <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"
              />
            </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={handleGstinChange}
                placeholder="e.g. 22AAAAA0000A1Z5"
                maxLength={15}
                required
                className={`h-9 text-sm font-mono ${gstinError ? "border-destructive" : ""}`}
              />
              {gstinError && (
                <p className="text-xs text-destructive">{gstinError}</p>
              )}
            </div>
          </div>

          {/* Logo Upload */}
          <div className="space-y-1.5">
            <Label className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
              Logo
            </Label>
            {preview ? (
              <div
                onClick={() => fileRef.current?.click()}
                className="relative 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"
              >
                <img
                  src={preview}
                  alt="logo preview"
                  className="h-16 w-auto object-contain rounded-lg"
                />
              </div>
            ) : (
              <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"
              >
                <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"
              size="sm"
              disabled={isPending}
              className="min-w-[160px]"
            >
              {isPending ? "Updating..." : "Update Organization"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
