"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import { Buildings, ImageSquare, CircleNotch, Trash } from '@/lib/icons';
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";

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 [uploading, startUpload] = useTransition();
  const [removing, startRemove] = useTransition();
  const [previewUrl, setPreviewUrl] = useState<string | null>(currentLogoUrl);
  const [dragOver, setDragOver] = useState(false);
  const [progress, setProgress] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const progressInterval = useRef<ReturnType<typeof setInterval> | null>(null);

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

  function startProgressAnimation() {
    setProgress(5);
    if (progressInterval.current) clearInterval(progressInterval.current);
    progressInterval.current = setInterval(() => {
      setProgress((p) => {
        if (p >= 85) return p;
        return p + Math.random() * 12 + 3;
      });
    }, 250);
  }

  function stopProgress(success: boolean) {
    if (progressInterval.current) clearInterval(progressInterval.current);
    if (success) {
      setProgress(100);
      setTimeout(() => setProgress(0), 1200);
    } else {
      setProgress(0);
    }
  }

  function uploadFile(file: File) {
    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;
    }

    // Show local preview immediately
    const reader = new FileReader();
    reader.onload = (e) => {
      if (typeof e.target?.result === "string") setPreviewUrl(e.target.result);
    };
    reader.readAsDataURL(file);

    // Auto-upload
    const formData = new FormData();
    formData.append("logo", file);
    startProgressAnimation();

    startUpload(async () => {
      const result = await uploadLogoAction(null, formData);
      stopProgress(result.ok);
      if (result.ok) {
        toast.success("Logo güncellendi.");
      } else {
        toast.error(result.error ?? "Logo yüklenemedi.");
        setPreviewUrl(currentLogoUrl); // revert preview
      }
    });
  }

  function handleInputChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (file) uploadFile(file);
    // reset so same file can be re-selected
    e.target.value = "";
  }

  function handleDrop(e: React.DragEvent<HTMLLabelElement>) {
    e.preventDefault();
    setDragOver(false);
    const file = e.dataTransfer.files?.[0];
    if (file) uploadFile(file);
  }

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

  const busy = uploading || removing;

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Buildings 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>
        <div className="grid items-start gap-6 md:grid-cols-[200px_1fr]">
          {/* Preview */}
          <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">
                <Buildings className="size-8 opacity-40" />
                <span>Henüz logo yok</span>
              </div>
            )}
          </div>

          <div className="space-y-3">
            {/* Drop zone — auto-uploads on select */}
            <label
              onDragOver={(e) => { e.preventDefault(); if (canEdit) setDragOver(true); }}
              onDragLeave={() => setDragOver(false)}
              onDrop={canEdit ? handleDrop : undefined}
              className={cn(
                "flex min-h-[120px] flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-6 text-center transition-colors",
                canEdit && !busy ? "cursor-pointer hover:bg-muted/30" : "cursor-not-allowed opacity-60",
                dragOver && "border-primary bg-primary/5",
              )}
            >
              <input
                ref={inputRef}
                type="file"
                accept={ALLOWED_MIME.join(",")}
                className="sr-only"
                disabled={!canEdit || busy}
                onChange={handleInputChange}
              />
              {uploading ? (
                <CircleNotch className="size-6 text-muted-foreground animate-spin" />
              ) : (
                <ImageSquare className="size-6 text-muted-foreground" />
              )}
              <div className="text-sm font-medium">
                {uploading ? "Yükleniyor…" : "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>

            {/* Progress bar */}
            {progress > 0 && (
              <div className="h-1.5 w-full rounded-full bg-muted overflow-hidden">
                <div
                  className={cn(
                    "h-full rounded-full transition-all",
                    progress === 100 ? "bg-green-500 duration-300" : "bg-primary duration-200",
                  )}
                  style={{ width: `${progress}%` }}
                />
              </div>
            )}

            {/* Remove button */}
            {canEdit && previewUrl && !uploading && (
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={handleRemove}
                disabled={busy}
                className="text-destructive hover:text-destructive"
              >
                {removing ? (
                  <CircleNotch className="size-4 animate-spin" />
                ) : (
                  <Trash className="size-4" />
                )}
                Logoyu Kaldır
              </Button>
            )}

            {!canEdit && (
              <p className="text-muted-foreground text-xs">
                Logo değiştirmek için yönetici yetkisi gerekli.
              </p>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
