"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { KeyRound, Save } from "lucide-react";
import { Card, CardHeader, CardContent, CardFooter } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input, Field, NativeSelect } from "@/components/ui/input";
import { updateOwnProfile, changeOwnPassword } from "@/lib/actions/workers";

export function ProfileForms({ initial, passwordMinLength }: { initial: { fullName: string; phone: string; locale: "en" | "fr" | "ar" }; passwordMinLength: number }) {
  const router = useRouter();
  const [p, setP] = React.useState(initial);
  const [pw, setPw] = React.useState({ current: "", next: "", confirm: "" });
  const [busy, setBusy] = React.useState<"profile" | "password" | null>(null);
  async function saveProfile() {
    setBusy("profile");
    const res = await updateOwnProfile(p);
    setBusy(null);
    if (!res.ok) return toast.error(res.error);
    toast.success("Profile updated");
    router.refresh();
  }
  async function savePassword() {
    if (pw.next !== pw.confirm) return toast.error("Passwords do not match");
    setBusy("password");
    const res = await changeOwnPassword({ current: pw.current, next: pw.next });
    setBusy(null);
    if (!res.ok) return toast.error(res.error);
    toast.success("Password changed. Other devices were signed out.");
    setPw({ current: "", next: "", confirm: "" });
    router.refresh();
  }
  return (
    <>
      <Card>
        <CardHeader title="Personal details" />
        <CardContent className="grid gap-4 sm:grid-cols-2">
          <Field label="Full name" required>
            <Input value={p.fullName} onChange={(e) => setP({ ...p, fullName: e.target.value })} />
          </Field>
          <Field label="Phone">
            <Input type="tel" value={p.phone} onChange={(e) => setP({ ...p, phone: e.target.value })} />
          </Field>
          <Field label="Interface language">
            <NativeSelect value={p.locale} onChange={(e) => setP({ ...p, locale: e.target.value as typeof p.locale })}>
              <option value="en">English</option>
              <option value="fr">Français</option>
              <option value="ar">العربية</option>
            </NativeSelect>
          </Field>
        </CardContent>
        <CardFooter className="justify-end">
          <Button size="sm" onClick={saveProfile} loading={busy === "profile"} disabled={JSON.stringify(p) === JSON.stringify(initial)}>
            <Save /> Save
          </Button>
        </CardFooter>
      </Card>
      <Card>
        <CardHeader title="Change password" description={`At least ${passwordMinLength} characters. Changing it signs out your other devices.`} />
        <CardContent className="grid gap-4 sm:grid-cols-3">
          <Field label="Current password" required>
            <Input type="password" autoComplete="current-password" value={pw.current} onChange={(e) => setPw({ ...pw, current: e.target.value })} />
          </Field>
          <Field label="New password" required>
            <Input type="password" autoComplete="new-password" value={pw.next} onChange={(e) => setPw({ ...pw, next: e.target.value })} />
          </Field>
          <Field label="Confirm new password" required error={pw.confirm && pw.confirm !== pw.next ? "Does not match" : undefined}>
            <Input type="password" autoComplete="new-password" value={pw.confirm} onChange={(e) => setPw({ ...pw, confirm: e.target.value })} />
          </Field>
        </CardContent>
        <CardFooter className="justify-end">
          <Button size="sm" variant="secondary" onClick={savePassword} loading={busy === "password"} disabled={!pw.current || pw.next.length < passwordMinLength || pw.next !== pw.confirm}>
            <KeyRound /> Change password
          </Button>
        </CardFooter>
      </Card>
    </>
  );
}
