import { createFileRoute } from "@tanstack/react-router";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
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 { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";
import { getInitials, useAuth } from "@/lib/auth/use-auth";
import { updateProfileFn } from "@/lib/auth/auth.functions";
import { ROLE_LABELS } from "@/lib/auth/roles";

export const Route = createFileRoute("/settings/profile")({
  component: ProfileSettings,
});

function ProfileSettings() {
  const { user, setUser, refresh } = useAuth();
  const [saving, setSaving] = useState(false);

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!user) return;
    const form = new FormData(e.currentTarget);
    setSaving(true);
    try {
      const result = await updateProfileFn({
        data: {
          firstName: String(form.get("firstName") ?? "").trim(),
          lastName: String(form.get("lastName") ?? "").trim(),
          organization: String(form.get("organization") ?? "").trim(),
        },
      });
      if (result.user) setUser(result.user as never);
      await refresh();
      toast.success("Profile updated");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not save changes.");
    } finally {
      setSaving(false);
    }
  };

  return (
    <form onSubmit={onSubmit} className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">Profile</CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center gap-4">
            <Avatar className="h-16 w-16">
              <AvatarFallback className="bg-gradient-to-br from-primary to-accent text-primary-foreground text-lg font-semibold">
                {getInitials(user)}
              </AvatarFallback>
            </Avatar>
            <div className="space-y-1">
              <Button type="button" variant="outline" size="sm" disabled>
                Upload photo
              </Button>
              <p className="text-xs text-muted-foreground">PNG or JPG, max 2MB.</p>
            </div>
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="fn">First name</Label>
              <Input id="fn" name="firstName" defaultValue={user?.firstName ?? ""} required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="ln">Last name</Label>
              <Input id="ln" name="lastName" defaultValue={user?.lastName ?? ""} required />
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label htmlFor="email">Work email</Label>
              <div className="flex gap-2">
                <Input id="email" type="email" defaultValue={user?.email ?? ""} disabled />
                {user?.emailVerified ? (
                  <Badge
                    variant="outline"
                    className="text-[10px] border-success/30 text-success self-center"
                  >
                    Verified
                  </Badge>
                ) : (
                  <Badge
                    variant="outline"
                    className="text-[10px] border-warning/30 text-warning-foreground self-center"
                  >
                    Unverified
                  </Badge>
                )}
              </div>
            </div>
            <div className="space-y-2 sm:col-span-2">
              <Label htmlFor="bio">Bio</Label>
              <Textarea id="bio" rows={3} placeholder="A short description for your team." />
            </div>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Organization</CardTitle>
        </CardHeader>
        <CardContent className="grid sm:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="org">Organization</Label>
            <Input id="org" name="organization" defaultValue={user?.organization ?? ""} />
          </div>
          <div className="space-y-2">
            <Label>Role</Label>
            <Input value={user ? ROLE_LABELS[user.role] : ""} disabled />
          </div>
        </CardContent>
      </Card>

      <div className="flex justify-end gap-2">
        <Button type="button" variant="outline" disabled={saving}>
          Cancel
        </Button>
        <Button type="submit" disabled={saving || !user}>
          {saving ? "Saving…" : "Save changes"}
        </Button>
      </div>
    </form>
  );
}
