"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ArrowLeft, Users, Mail } from "lucide-react";
import { useInviteClient } from "../hooks/client.hooks";
import { capitalizeFirstLetter } from "@/lib/capitalize";

const FieldError = ({ msg }: { msg?: string }) =>
  msg ? <p className="mt-1 text-xs text-destructive">{msg}</p> : null;

export function CreateClientPage() {
  const router = useRouter();
  const [form, setForm] = useState({
    name: "",
    email: "",
    companyName: "",
    gstin: "",
    pan: "",
    phone: "",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const { mutate, isPending } = useInviteClient(() =>
    router.push("/admin/clients")
  );

  const set = (key: string, value: string) => {
    setForm((prev) => ({ ...prev, [key]: value }));
    setErrors((prev) => {
      const n = { ...prev };
      delete n[key];
      return n;
    });
  };

  const validate = () => {
    const e: Record<string, string> = {};
    if (!form.name.trim()) e.name = "Full name is required";
    if (!form.email.trim()) e.email = "Email is required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email))
      e.email = "Enter a valid email";
    return e;
  };

  const handleSubmit = () => {
    const e = validate();
    if (Object.keys(e).length) {
      setErrors(e);
      return;
    }
    setErrors({});
    mutate({
      name: capitalizeFirstLetter(form.name.trim()),
      email: form.email.trim(),
      ...(form.companyName ? { companyName: form.companyName.trim() } : {}),
      ...(form.gstin ? { gstin: form.gstin.trim() } : {}),
      ...(form.pan ? { pan: form.pan.trim() } : {}),
      ...(form.phone ? { phone: form.phone.trim() } : {}),
    });
  };

  const initials = form.name
    .split(" ")
    .map((n) => n[0])
    .join("")
    .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">Add Client</h2>
        <p className="text-muted-foreground text-sm mt-0.5">
          Send an invitation to a new client
        </p>
      </div>

      <div className="flex flex-col md:flex-row gap-5 items-start w-full">
        {/* LEFT CARD */}
        <div className="flex flex-col gap-4">
          <Card className="p-6 flex flex-col items-center gap-3 flex-1">
            <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>
              ) : (
                <Users className="h-8 w-8 text-muted-foreground" />
              )}
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold">
                {form.name || "New Client"}
              </p>
              <p className="text-xs text-muted-foreground">
                {form.email || "Enter email below"}
              </p>
            </div>
          </Card>

          <div className="border rounded-xl p-4 flex gap-3">
            <Mail className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
            <p className="text-xs text-muted-foreground leading-relaxed">
              An invitation email will be sent to the client. They can set their
              password via the link.
            </p>
          </div>
        </div>

        {/* RIGHT FORM */}
        <Card className="p-6 flex flex-col w-full">
          <p className="text-sm font-semibold flex items-center gap-2 mb-5">
            <Users className="h-4 w-4 text-primary" /> Client Information
          </p>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Full Name <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="e.g. Rahul Sharma"
                value={form.name}
                onChange={(e) => set("name", e.target.value)}
                className={errors.name ? "border-destructive" : ""}
              />
              <FieldError msg={errors.name} />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Email Address <span className="text-destructive">*</span>
              </Label>
              <Input
                type="email"
                placeholder="e.g. rahul@example.com"
                value={form.email}
                onChange={(e) => set("email", e.target.value)}
                className={errors.email ? "border-destructive" : ""}
              />
              <FieldError msg={errors.email} />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Company Name
              </Label>
              <Input
                placeholder="e.g. Acme Pvt Ltd"
                value={form.companyName}
                onChange={(e) => set("companyName", e.target.value)}
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                Phone
              </Label>
              <Input
                placeholder="e.g. 9876543210"
                value={form.phone}
                onChange={(e) => set("phone", e.target.value)}
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                GSTIN
              </Label>
              <Input
                placeholder="e.g. 22AAAAA0000A1Z5"
                value={form.gstin}
                onChange={(e) => set("gstin", e.target.value)}
              />
            </div>

            <div className="space-y-1.5">
              <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                PAN
              </Label>
              <Input
                placeholder="e.g. AAAAA0000A"
                value={form.pan}
                onChange={(e) => set("pan", e.target.value)}
              />
            </div>
          </div>

          <div className="flex items-center justify-end gap-3 mt-8 pt-6">
            <Button
              variant="ghost"
              className="border border-border hover:bg-muted hover:text-foreground"
              onClick={() => router.back()}
            >
              Cancel
            </Button>
            <Button type="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" />
              )}
              Create Client
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}
