"use client";

import { useActionState, useEffect } from "react";
import { Building2, Coins, Loader2, Save } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { updateWorkspaceSettingsAction } from "@/lib/appwrite/workspace-actions";
import { initialWorkspaceSettingsState } from "@/lib/appwrite/workspace-types";

type Defaults = {
  companyName: string;
  companyTaxId: string;
  companyAddress: string;
  companyEmail: string;
  companyPhone: string;
  defaultCurrency: string;
  kind: "lab" | "clinic" | null;
  memberNumber: string;
};

export function WorkspaceSettingsForm({
  canEdit,
  defaults,
}: {
  canEdit: boolean;
  defaults: Defaults;
}) {
  const [state, formAction, isPending] = useActionState(
    updateWorkspaceSettingsAction,
    initialWorkspaceSettingsState,
  );

  useEffect(() => {
    if (state.ok) toast.success("Bilgiler güncellendi.");
    else if (state.error) toast.error(state.error);
  }, [state]);

  const kindLabel = defaults.kind === "lab" ? "Laboratuvar" : defaults.kind === "clinic" ? "Klinik" : "—";

  return (
    <form action={formAction} className="space-y-6">
      <fieldset disabled={!canEdit || isPending} className="space-y-6 disabled:opacity-90">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Building2 className="size-4" />
              Şirket
            </CardTitle>
            <CardDescription>Resmi şirket bilgileriniz ve bağlantı kodunuz.</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-5 md:grid-cols-2">
            <div className="grid gap-2">
              <Label>Hesap türü</Label>
              <div className="bg-muted/50 flex h-9 items-center rounded-md border px-3 text-sm">
                {kindLabel}
              </div>
            </div>
            <div className="grid gap-2">
              <Label>Bağlantı kodu</Label>
              <div className="bg-muted/50 flex h-9 items-center rounded-md border px-3 font-mono text-sm tracking-widest">
                {defaults.memberNumber || "—"}
              </div>
            </div>

            <div className="md:col-span-2 grid gap-2">
              <Label htmlFor="companyName">Şirket adı *</Label>
              <Input
                id="companyName"
                name="companyName"
                defaultValue={defaults.companyName}
                required
                placeholder="Örn. Atlas Diş Polikliniği"
              />
              {state.fieldErrors?.companyName && (
                <p className="text-destructive text-xs">{state.fieldErrors.companyName}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="companyTaxId">Vergi numarası</Label>
              <Input
                id="companyTaxId"
                name="companyTaxId"
                defaultValue={defaults.companyTaxId}
                inputMode="numeric"
                placeholder="1234567890"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="companyPhone">Telefon</Label>
              <Input
                id="companyPhone"
                name="companyPhone"
                type="tel"
                defaultValue={defaults.companyPhone}
                placeholder="+90 555 123 45 67"
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="companyEmail">Email</Label>
              <Input
                id="companyEmail"
                name="companyEmail"
                type="email"
                defaultValue={defaults.companyEmail}
                placeholder="info@firma.com"
              />
              {state.fieldErrors?.companyEmail && (
                <p className="text-destructive text-xs">{state.fieldErrors.companyEmail}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="companyAddress">Adres</Label>
              <Textarea
                id="companyAddress"
                name="companyAddress"
                rows={2}
                defaultValue={defaults.companyAddress}
                placeholder="İl, ilçe, açık adres"
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Coins className="size-4" />
              Finans varsayılanları
            </CardTitle>
            <CardDescription>Yeni iş ve faturalarda kullanılan varsayılanlar.</CardDescription>
          </CardHeader>
          <CardContent className="grid gap-5 md:grid-cols-3">
            <div className="grid gap-2">
              <Label htmlFor="defaultCurrency">Varsayılan para birimi</Label>
              <Input
                id="defaultCurrency"
                name="defaultCurrency"
                defaultValue={defaults.defaultCurrency}
                maxLength={8}
                placeholder="TRY"
                style={{ textTransform: "uppercase" }}
              />
            </div>
          </CardContent>
        </Card>

        {canEdit && (
          <div className="flex justify-end">
            <Button type="submit" disabled={isPending}>
              {isPending ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Kaydediliyor...
                </>
              ) : (
                <>
                  <Save className="size-4" />
                  Kaydet
                </>
              )}
            </Button>
          </div>
        )}
      </fieldset>
    </form>
  );
}
