"use client";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { FolderDocumentIcon } from "@/components/icons/folder-document-icon";
import { usePhases } from "@/hooks/use-phases";
import { useProjectFiles } from "@/hooks/use-files";
import type { ProjectFile } from "@/lib/api/types";
import { cn } from "@/lib/utils";
import { ArrowRight, ChevronLeft, Search, X } from "lucide-react";
import { useState, useMemo } from "react";
import { SelectableFileCard } from "./selectable-file-card";

interface MediaLibraryDialogTranslations {
  title: string;
  selectPhase: string;
  selectFiles: string;
  phase: string;
  files: string;
  noPhases: string;
  noFiles: string;
  searchPlaceholder: string;
  cancel: string;
  confirm: string;
  back: string;
  selectedCount: string;
}

interface MediaLibraryDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  projectId: string | number;
  onSelectFiles: (files: ProjectFile[]) => void;
  translations: MediaLibraryDialogTranslations;
  locale: "ar" | "en";
}

type DialogStep = "phases" | "files";

export function MediaLibraryDialog({
  open,
  onOpenChange,
  projectId,
  onSelectFiles,
  translations,
  locale,
}: MediaLibraryDialogProps) {
  const [step, setStep] = useState<DialogStep>("phases");
  const [selectedPhaseId, setSelectedPhaseId] = useState<number | null>(null);
  const [selectedFileIds, setSelectedFileIds] = useState<Set<number>>(
    new Set()
  );
  const [searchQuery, setSearchQuery] = useState("");

  // Fetch phases for the project
  const { phases, isLoading: isPhasesLoading } = usePhases({
    projectId: projectId?.toString(),
  });

  // Fetch files for the selected phase
  const { files, isLoading: isFilesLoading } = useProjectFiles(
    selectedPhaseId ? projectId : null,
    {
      phase_id: selectedPhaseId ?? undefined,
      search: searchQuery || undefined,
    }
  );

  // Filter phases that have files (tasks_count could indicate file count in context)
  const phasesWithInfo = useMemo(() => {
    return phases || [];
  }, [phases]);

  // Filter files based on search
  const filteredFiles = useMemo(() => {
    if (!files) return [];
    if (!searchQuery) return files;
    return files.filter((file) =>
      file.file_name.toLowerCase().includes(searchQuery.toLowerCase())
    );
  }, [files, searchQuery]);

  const handlePhaseSelect = (phaseId: number) => {
    setSelectedPhaseId(phaseId);
    setStep("files");
    setSearchQuery("");
  };

  const handleBack = () => {
    setStep("phases");
    setSelectedPhaseId(null);
    setSearchQuery("");
  };

  const handleFileSelect = (fileId: number) => {
    setSelectedFileIds((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(fileId)) {
        newSet.delete(fileId);
      } else {
        newSet.add(fileId);
      }
      return newSet;
    });
  };

  const handleConfirm = () => {
    if (files && selectedFileIds.size > 0) {
      const selectedFiles = files.filter((f) => selectedFileIds.has(f.id));
      onSelectFiles(selectedFiles);
      handleClose();
    }
  };

  const handleClose = () => {
    setStep("phases");
    setSelectedPhaseId(null);
    setSelectedFileIds(new Set());
    setSearchQuery("");
    onOpenChange(false);
  };

  const selectedPhase = phasesWithInfo.find((p) => p.id === selectedPhaseId);

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[900px]">
        {/* Header */}
        <DialogHeader className="border-border">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              {step === "files" && (
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={handleBack}
                  className="h-8 w-8"
                >
                  {locale === "ar" ? (
                    <ArrowRight className="h-4 w-4" />
                  ) : (
                    <ChevronLeft className="h-4 w-4" />
                  )}
                </Button>
              )}
              <DialogTitle className="text-lg font-semibold">
                {translations.title}
              </DialogTitle>
            </div>
          </div>

          {/* Breadcrumb / Step Indicator */}
          <div className="flex items-center gap-2 mt-2 text-sm text-muted-foreground">
            <span
              className={cn(step === "phases" && "text-primary font-medium")}
            >
              {translations.selectPhase}
            </span>
            {step === "files" && selectedPhase && (
              <>
                <span>/</span>
                <span className="text-primary font-medium">
                  {selectedPhase.name}
                </span>
              </>
            )}
          </div>
        </DialogHeader>

        {/* Content */}
        <DialogBody className="py-4">
          {step === "phases" ? (
            // Step 1: Phase Selection Grid
            <div className="space-y-4">
              {isPhasesLoading ? (
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
                </div>
              ) : phasesWithInfo.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  {translations.noPhases}
                </div>
              ) : (
                <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
                  {phasesWithInfo.map((phase) => (
                    <div
                      key={phase.id}
                      className={cn(
                        "bg-background border border-border rounded-lg overflow-hidden cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/50 group"
                      )}
                      onClick={() => handlePhaseSelect(phase.id)}
                      role="button"
                      tabIndex={0}
                      onKeyDown={(e) => {
                        if (e.key === "Enter" || e.key === " ") {
                          e.preventDefault();
                          handlePhaseSelect(phase.id);
                        }
                      }}
                    >
                      {/* Icon Container */}
                      <div className="h-[120px] overflow-hidden flex items-center justify-center">
                        <FolderDocumentIcon className="w-20 h-20 transition-transform duration-200 group-hover:scale-110" />
                      </div>

                      {/* Phase Info */}
                      <div className="flex flex-col gap-2 px-4 py-2 w-full">
                        <p className="text-sm font-medium text-foreground  leading-5 line-clamp-2">
                          {phase.name}
                        </p>
                        {/* <p className="text-xs text-muted-foreground  leading-5">
                          {phase.tasks_count || 0} {translations.files}
                        </p> */}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : (
            // Step 2: File Selection Grid
            <div className="space-y-4">
              {/* Search Bar */}
              <div className="relative">
                <Search className="absolute start-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder={translations.searchPlaceholder}
                  className="ps-9 h-10"
                />
                {searchQuery && (
                  <button
                    type="button"
                    onClick={() => setSearchQuery("")}
                    className="absolute end-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                  >
                    <X className="h-4 w-4" />
                  </button>
                )}
              </div>

              {/* Files Grid */}
              {isFilesLoading ? (
                <div className="flex items-center justify-center py-12">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
                </div>
              ) : filteredFiles.length === 0 ? (
                <div className="text-center py-12 text-muted-foreground">
                  {translations.noFiles}
                </div>
              ) : (
                <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
                  {filteredFiles.map((file) => (
                    <SelectableFileCard
                      key={file.id}
                      file={file}
                      selected={selectedFileIds.has(file.id)}
                      onSelect={handleFileSelect}
                    />
                  ))}
                </div>
              )}
            </div>
          )}
        </DialogBody>

        {/* Footer */}
        <DialogFooter className="items-center justify-between gap-3">
          <div className="flex items-center justify-between gap-3">
            <div className="flex items-center gap-3">
              {step === "files" && (
                <Button
                  onClick={handleConfirm}
                  disabled={selectedFileIds.size === 0}
                  className="h-10 px-6"
                >
                  {translations.confirm}
                  {selectedFileIds.size > 0 && (
                    <span className="ms-2 text-xs">
                      ({selectedFileIds.size})
                    </span>
                  )}
                </Button>
              )}
            </div>
            <Button
              variant="outline"
              onClick={handleClose}
              className="h-10 px-6"
            >
              {translations.cancel}
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
