"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { Card } from "@/components/ui/card";
import { MediaPickerButton } from "@/components/admin/media-picker";
import { toast } from "sonner";
import { Loader2, Save, Trash2 } from "lucide-react";

export type TeamFormValues = {
  id?: string;
  name: string;
  position: string;
  bio: string;
  image: string | null;
  order: number;
  isEnabled: boolean;
};

export function TeamForm({ initial, isNew }: { initial?: TeamFormValues; isNew?: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = React.useState(false);
  const [values, setValues] = React.useState<TeamFormValues>(
    initial || {
      name: "",
      position: "",
      bio: "",
      image: null,
      order: 0,
      isEnabled: true,
    }
  );

  const set = <K extends keyof TeamFormValues>(k: K, v: TeamFormValues[K]) =>
    setValues((prev) => ({ ...prev, [k]: v }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!values.name.trim()) return toast.error("Name is required");
    if (!values.position.trim()) return toast.error("Position is required");
    setLoading(true);
    try {
      const url = isNew ? "/api/admin/team" : `/api/admin/team/${values.id}`;
      const res = await fetch(url, {
        method: isNew ? "POST" : "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(values),
      });
      if (!res.ok) {
        const d = await res.json();
        throw new Error(d.error || "Failed");
      }
      toast.success(isNew ? "Team member created" : "Team member updated");
      router.push("/admin/team");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    if (!confirm("Delete this team member? This cannot be undone.")) return;
    setLoading(true);
    try {
      await fetch(`/api/admin/team/${values.id}`, { method: "DELETE" });
      toast.success("Team member deleted");
      router.push("/admin/team");
      router.refresh();
    } catch {
      toast.error("Delete failed");
    } finally {
      setLoading(false);
    }
  };

  const initials = values.name
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase() ?? "")
    .join("");

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-5">
          <Card className="p-6 rounded-2xl space-y-5">
            <h2 className="font-bold text-lg">Member Details</h2>
            <div className="space-y-1.5">
              <Label>Name *</Label>
              <Input
                value={values.name}
                onChange={(e) => set("name", e.target.value)}
                placeholder="e.g. Hasan Raza"
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label>Position *</Label>
              <Input
                value={values.position}
                onChange={(e) => set("position", e.target.value)}
                placeholder="e.g. Senior HVAC Engineer"
                required
              />
            </div>
            <div className="space-y-1.5">
              <Label>Bio</Label>
              <Textarea
                rows={5}
                value={values.bio}
                onChange={(e) => set("bio", e.target.value)}
                placeholder="Brief background, certifications, expertise..."
              />
            </div>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-5">
          <Card className="p-6 rounded-2xl space-y-4">
            <h2 className="font-bold">Status</h2>
            <div className="flex items-center justify-between">
              <Label htmlFor="enabled">Enabled</Label>
              <Switch
                id="enabled"
                checked={values.isEnabled}
                onCheckedChange={(v) => set("isEnabled", v)}
              />
            </div>
            <div className="space-y-1.5">
              <Label>Display Order</Label>
              <Input
                type="number"
                value={values.order}
                onChange={(e) => set("order", parseInt(e.target.value) || 0)}
              />
              <p className="text-xs text-muted-foreground">Lower numbers appear first.</p>
            </div>
          </Card>
          <Card className="p-6 rounded-2xl space-y-3">
            <h2 className="font-bold">Profile Photo</h2>
            {values.image ? (
              <img src={values.image} alt={values.name} className="size-24 rounded-2xl object-cover border border-border" />
            ) : (
              <div className="size-24 rounded-2xl bg-[var(--brand-royal)]/10 text-[var(--brand-royal)] grid place-items-center font-bold text-xl">
                {initials || "—"}
              </div>
            )}
            <MediaPickerButton value={values.image} onChange={(v) => set("image", v)} accept="image" label="Upload Photo" />
          </Card>
          <div className="flex flex-col gap-2">
            <Button type="submit" disabled={loading} className="brand-gradient text-white">
              {loading ? <Loader2 className="size-4 mr-2 animate-spin" /> : <Save className="size-4 mr-2" />}
              {isNew ? "Create Member" : "Save Changes"}
            </Button>
            <Button type="button" variant="outline" onClick={() => router.back()}>Cancel</Button>
            {!isNew && (
              <Button type="button" variant="ghost" className="text-destructive" onClick={onDelete} disabled={loading}>
                <Trash2 className="size-4 mr-2" /> Delete Member
              </Button>
            )}
          </div>
        </div>
      </div>
    </form>
  );
}
