"use client";

import { useActionState, useEffect, useRef, useState, useTransition } from "react";
import { Building2, ImagePlus, Loader2, Trash2, Upload } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { cn } from "@/lib/utils";
import {
  removeLogoAction,
  uploadLogoAction,
} from "@/lib/appwrite/logo-actions";
import { initialLogoState } from "@/lib/appwrite/logo-types";

type Props = {
  canEdit: boolean;
  currentLogoUrl: string | null;
  companyName: string;
};

const MAX_BYTES = 2 * 1024 * 1024;
const ALLOWED_MIME = ["image/png", "image/jpeg", "image/webp", "image/svg+xml"];

export function LogoUploader({ canEdit, currentLogoUrl, companyName }: Props) {
  const [state, formAction, isPending] = useActionState(
    uploadLogoAction,
    initialLogoState,
  );
  const [removing, startRemove] = useTransition();
  const [previewUrl, setPreviewUrl] = useState<string | null>(currentLogoUrl);
  const [dragOver, setDragOver] = useState(false);
  const [selectedName, setSelectedName] = useState<string | null>(null);
  const formRef = useRef<HTMLFormElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    setPreviewUrl(currentLogoUrl);
  }, [currentLogoUrl]);

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

  const handleFile = (file: File | null) => {
    if (!file) return;
    if (!ALLOWED_MIME.includes(file.type)) {
      toast.error("Sadece PNG, JPG, WebP veya SVG yükleyebilirsiniz.");
      return;
    }
    if (file.size > MAX_BYTES) {
      toast.error("Dosya 2MB'dan büyük olamaz.");
      return;
    }
    setSelectedName(file.name);
    const reader = new FileReader();
    reader.onload = (e) => {
      setPreviewUrl(typeof e.target?.result === "string" ? e.target.result : null);
    };
    reader.readAsDataURL(file);
  };

  const handleDrop = (e: React.DragEvent<HTMLLabelElement>) => {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files?.[0];
    if (file && inputRef.current) {
      const dt = new DataTransfer();
      dt.items.add(file);
      inputRef.current.files = dt.files;
      handleFile(file);
    }
  };

  const handleRemove = () => {
    startRemove(async () => {
      const result = await removeLogoAction();
      if (result.ok) {
        toast.success("Logo kaldırıldı.");
        setPreviewUrl(null);
        setSelectedName(null);
        if (inputRef.current) inputRef.current.value = "";
      } else {
        toast.error(result.error ?? "Logo kaldırılamadı.");
      }
    });
  };

  const submitDisabled = isPending || removing || !selectedName;
  const busy = isPending || removing;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Building2 className="size-4" />
          Logo
        </CardTitle>
        <CardDescription>
          Faturalarda, panel başlığında ve dış paylaşımlarda görünür. PNG, JPG, WebP veya SVG —
          en fazla 2 MB.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form ref={formRef} action={formAction} className="space-y-4">
          <div className="grid items-start gap-6 md:grid-cols-[200px_1fr]">
            <div className="bg-muted flex aspect-square w-full items-center justify-center overflow-hidden rounded-lg border">
              {previewUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={previewUrl}
                  alt={`${companyName} logo`}
                  className="size-full object-contain"
                />
              ) : (
                <div className="text-muted-foreground flex flex-col items-center gap-2 p-4 text-center text-xs">
                  <Building2 className="size-8 opacity-40" />
                  <span>Henüz logo yok</span>
                </div>
              )}
            </div>

            <div className="space-y-3">
              <label
                onDragOver={(e) => {
                  e.preventDefault();
                  if (canEdit) setDragOver(true);
                }}
                onDragLeave={() => setDragOver(false)}
                onDrop={canEdit ? handleDrop : undefined}
                className={cn(
                  "flex min-h-[120px] cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-6 text-center transition-colors",
                  dragOver && "border-primary bg-primary/5",
                  !canEdit && "cursor-not-allowed opacity-60",
                  !dragOver && "hover:bg-muted/30",
                )}
              >
                <input
                  ref={inputRef}
                  type="file"
                  name="logo"
                  accept={ALLOWED_MIME.join(",")}
                  className="sr-only"
                  disabled={!canEdit || busy}
                  onChange={(e) => handleFile(e.target.files?.[0] ?? null)}
                />
                <ImagePlus className="text-muted-foreground size-6" />
                <div className="text-sm font-medium">
                  {selectedName ?? "Logo yüklemek için tıkla veya sürükle bırak"}
                </div>
                <div className="text-muted-foreground text-xs">
                  Önerilen: kare, en az 256×256 px, şeffaf arka plan (PNG/SVG)
                </div>
              </label>

              <div className="flex flex-wrap gap-2">
                {canEdit && (
                  <Button type="submit" disabled={submitDisabled}>
                    {isPending ? (
                      <>
                        <Loader2 className="size-4 animate-spin" />
                        Yükleniyor...
                      </>
                    ) : (
                      <>
                        <Upload className="size-4" />
                        Yükle
                      </>
                    )}
                  </Button>
                )}
                {canEdit && currentLogoUrl && (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={handleRemove}
                    disabled={busy}
                    className="text-destructive hover:text-destructive"
                  >
                    {removing ? (
                      <Loader2 className="size-4 animate-spin" />
                    ) : (
                      <Trash2 className="size-4" />
                    )}
                    Kaldır
                  </Button>
                )}
                {!canEdit && (
                  <p className="text-muted-foreground text-xs">
                    Logo değiştirmek için yönetici yetkisi gerekli.
                  </p>
                )}
              </div>
            </div>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
