"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { ArrowLeft, Building2, Info } from "lucide-react";
import {
  useGetDepartment,
  useUpdateDepartment,
} from "../hooks/department.hook";
import { capitalizeFirstLetter } from "@/lib/capitalize";
import { formatDateTime } from "@/lib/format-date";

interface Props {
  id: string;
}

export function EditDepartmentPage({ id }: Props) {
  const router = useRouter();
  const { data: dept, isLoading } = useGetDepartment(id);
  const [name, setName] = useState("");
  const [error, setError] = useState("");
  const { mutate, isPending } = useUpdateDepartment(() =>
    router.push("/admin/departments")
  );

  useEffect(() => {
    if (dept) setName(dept.name);
  }, [dept]);

  const handleSubmit = () => {
    if (!name.trim()) {
      setError("Department name is required");
      return;
    }

    setError("");

    mutate({
      id,
      payload: {
        name: capitalizeFirstLetter(name.trim()),
      },
    });
  };

  const initials = name.trim().slice(0, 2).toUpperCase();

  return (
    <div className="space-y-4">
      <button
        onClick={() => router.back()}
        className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
      >
        <ArrowLeft className="h-4 w-4" /> Back
      </button>
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Edit Department</h2>
        <p className="text-muted-foreground text-sm mt-0.5">
          Update department information
        </p>
      </div>

      <div className="flex flex-col md:flex-row gap-5 items-start w-full">
        {/* LEFT */}
        <div className="flex flex-col gap-4">
          <Card>
            <CardContent className="p-6 flex flex-col items-center gap-3">
              <div className="w-20 h-20 rounded-xl bg-muted flex items-center justify-center">
                {initials ? (
                  <span className="text-2xl font-bold text-primary">
                    {initials}
                  </span>
                ) : (
                  <Building2 className="h-8 w-8 text-muted-foreground" />
                )}
              </div>
              <div className="text-center">
                <p className="text-sm font-semibold">{name || "Department"}</p>

                {dept && (
                  <p className="text-xs text-muted-foreground">
                    Created {formatDateTime(dept.createdAt)}
                  </p>
                )}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="p-4 flex gap-3">
              <Info className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
              <p className="text-xs text-muted-foreground leading-relaxed">
                Renaming a department will update it across all assigned
                employees.
              </p>
            </CardContent>
          </Card>
        </div>

        {/* RIGHT */}
        <Card className="w-full max-w-lg">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="h-4 w-4 text-primary" />
              Department Details
            </CardTitle>
          </CardHeader>

          <CardContent>
            {isLoading ? (
              <div className="space-y-3">
                <Skeleton className="h-9 w-full" />
                <Skeleton className="h-9 w-32" />
              </div>
            ) : (
              <>
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Department Name <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    placeholder="e.g. Human Resources"
                    value={name}
                    onChange={(e) => {
                      setName(e.target.value);
                      setError("");
                    }}
                    className={error ? "border-destructive" : ""}
                  />
                  {error && (
                    <p className="text-xs text-destructive mt-1">{error}</p>
                  )}
                </div>

                <div className="flex items-center justify-end gap-3 mt-10 pt-4 border-t border-border">
                  <Button
                    variant="ghost"
                    className="border border-border hover:bg-muted hover:text-foreground"
                    onClick={() => router.back()}
                  >
                    Cancel
                  </Button>
                  <Button onClick={handleSubmit} disabled={isPending}>
                    {isPending && (
                      <div className="w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2" />
                    )}
                    Save Changes
                  </Button>
                </div>
              </>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
