"use client";

import { useState, useEffect } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { ArrowLeft, Users, Mail } from "lucide-react";
import { useGetClient, useUpdateClient } 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;

const CLIENT_STATUSES = [
  { value: "ACTIVE", label: "Active" },
  { value: "INVITED", label: "Invited" },
  { value: "SUSPENDED", label: "Suspended" },
  { value: "REVOKED", label: "Revoked" },
];

interface Props {
  id: string;
}

export function EditClientPage({ id }: Props) {
  const router = useRouter();
  const { data: client, isLoading } = useGetClient(id);
  const [form, setForm] = useState({
    name: "",
    companyName: "",
    gstin: "",
    pan: "",
    phone: "",
    status: "ACTIVE",
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

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

  useEffect(() => {
    if (client) {
      setForm({
        name: client.name ?? "",
        companyName: client.companyName ?? "",
        gstin: client.gstin ?? "",
        pan: client.pan ?? "",
        phone: client.phone ?? "",
        status: client.status ?? "ACTIVE",
      });
    }
  }, [client]);

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

  const handleSubmit = () => {
    const newErrors: Record<string, string> = {};
    if (!form.name.trim()) newErrors.name = "Full name is required";
    if (Object.keys(newErrors).length) {
      setErrors(newErrors);
      return;
    }
    setErrors({});
    mutate({
      name: capitalizeFirstLetter(form.name.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() } : {}),
      status: form.status,
    });
  };

  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">Edit Client</h2>
        <p className="text-muted-foreground text-sm mt-0.5">
          Update client information
        </p>
      </div>

      {isLoading ? (
        <div className="flex flex-col md:flex-row gap-5 items-start">
          <Card className="p-6">
            <Skeleton className="h-40 w-64" />
          </Card>
          <Card className="flex-1 p-6 space-y-4">
            {[1, 2, 3, 4].map((i) => (
              <Skeleton key={i} className="h-10 w-full" />
            ))}
          </Card>
        </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">
              <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 || "Client"}</p>
                <p className="text-xs text-muted-foreground">
                  {client?.email ?? "—"}
                </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">
                Email cannot be changed after invitation. Contact admin to
                update email.
              </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-xs normal-case font-normal">
                    (cannot be changed)
                  </span>
                </Label>
                <Input
                  type="email"
                  value={client?.email ?? ""}
                  disabled
                  className="bg-muted text-muted-foreground cursor-not-allowed"
                />
              </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 className="space-y-1.5">
                <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Status
                </Label>
                <Select
                  value={form.status}
                  onValueChange={(v) => set("status", v)}
                >
                  <SelectTrigger className="h-9 text-sm w-full">
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    {CLIENT_STATUSES.map((s) => (
                      <SelectItem key={s.value} value={s.value}>
                        {s.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </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" />
                )}
                Save Changes
              </Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}
