import { useTranslations } from "@/providers/TranslationProviders";
import {
  ChartBarIcon,
  DownloadIcon,
  FileDashedIcon,
  FileDocIcon,
  FileIcon,
  FileImageIcon,
  FilePdfIcon,
  FilePptIcon,
  FileZipIcon,
} from "phosphor-react-native";
import { useState } from "react";
import { ActivityIndicator, Platform, Pressable, Text, View } from "react-native";
import * as FileSystem from "expo-file-system/legacy";
import * as Sharing from "expo-sharing";
import { API_BASE_URL, TOKEN_NAME } from "@/configs";
import { storage } from "@/configs/storage";
import { useColor } from "@/hooks/useColor";
import { showToast } from "@/utils/toast";

interface Document {
  id: number;
  project_id: number;
  title: string;
  description?: string;
  file: string;
  status: string;
  created_at: string;
  updated_at: string;
}

interface DocumentsProps {
  documents?: Document[];
}

const getFileIcon = (filePath?: string | null) => {
  if (!filePath) {
    return {
      icon: FileIcon,
      bgColor: "bg-gray-50",
      iconColor: "text-gray-600",
    };
  }
  const extension = filePath.split(".").pop()?.toLowerCase();

  switch (extension) {
    case "pdf":
      return {
        icon: FilePdfIcon,
        bgColor: "bg-red-50",
        iconColor: "text-red-600",
      };
    case "xlsx":
    case "xls":
      return {
        icon: ChartBarIcon,
        bgColor: "bg-green-50",
        iconColor: "text-green-600",
      };
    case "docx":
    case "doc":
      return {
        icon: FileDocIcon,
        bgColor: "bg-blue-50",
        iconColor: "text-blue-600",
      };
    case "pptx":
    case "ppt":
      return {
        icon: FilePptIcon,
        bgColor: "bg-orange-50",
        iconColor: "text-orange-600",
      };
    case "zip":
    case "rar":
      return {
        icon: FileZipIcon,
        bgColor: "bg-purple-50",
        iconColor: "text-purple-600",
      };
    case "jpg":
    case "jpeg":
    case "png":
    case "gif":
      return {
        icon: FileImageIcon,
        bgColor: "bg-pink-50",
        iconColor: "text-pink-600",
      };
    default:
      return {
        icon: FileIcon,
        bgColor: "bg-gray-50",
        iconColor: "text-gray-600",
      };
  }
};

export default function Documents({ documents }: DocumentsProps) {
  const { tran } = useTranslations();
  const { primary } = useColor();
  const [downloadingId, setDownloadingId] = useState<number | null>(null);

  const activeDocuments = documents?.filter((doc) => doc.status === "active");

  const mimeFromExt = (ext?: string) => {
    switch (ext?.toLowerCase()) {
      case "pdf": return "application/pdf";
      case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      case "xls": return "application/vnd.ms-excel";
      case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      case "doc": return "application/msword";
      case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
      case "ppt": return "application/vnd.ms-powerpoint";
      case "zip": return "application/zip";
      case "rar": return "application/vnd.rar";
      case "jpg": case "jpeg": return "image/jpeg";
      case "png": return "image/png";
      case "gif": return "image/gif";
      default: return "application/octet-stream";
    }
  };

  const handleDownload = async (doc: Document) => {
    if (downloadingId) return;
    setDownloadingId(doc.id);
    try {
      const token = storage.getString(TOKEN_NAME);
      const rawName = doc.file.split("/").pop() || `document_${doc.id}`;
      const safeName = rawName.replace(/[^a-zA-Z0-9._-]/g, "_");
      const ext = safeName.split(".").pop();
      const mimeType = mimeFromExt(ext);
      const fileUri = `${FileSystem.cacheDirectory}${safeName}`;

      const downloadUrl = `${API_BASE_URL}/client/projects/${doc.project_id}/documents/${doc.id}${token ? `?token=${token}` : ""}`;
      const result = await FileSystem.downloadAsync(downloadUrl, fileUri);
      if (result.status < 200 || result.status >= 300) {
        showToast({ type: "error", text: tran("Failed to download document") + ` (${result.status})` });
        return;
      }

      if (Platform.OS === "android") {
        const permissions = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();
        if (permissions.granted) {
          const base64 = await FileSystem.readAsStringAsync(result.uri, { encoding: FileSystem.EncodingType.Base64 });
          const destUri = await FileSystem.StorageAccessFramework.createFileAsync(permissions.directoryUri, safeName, mimeType);
          await FileSystem.writeAsStringAsync(destUri, base64, { encoding: FileSystem.EncodingType.Base64 });
          showToast({ type: "success", text: tran("Document saved successfully") });
          return;
        }
      }

      if (await Sharing.isAvailableAsync()) {
        await Sharing.shareAsync(result.uri, { mimeType, dialogTitle: tran(doc.title) });
      } else {
        showToast({ type: "success", text: tran("Saved to") + " " + result.uri });
      }
    } catch (err: any) {
      console.warn("Download error:", err);
      showToast({ type: "error", text: err?.message || tran("Failed to download document") });
    } finally {
      setDownloadingId(null);
    }
  };

  return (
    <View>
      <View className="flex-row items-center justify-between mb-5">
        <Text className="text-xl font-manrope-extrabold text-slate-900">
          {tran("Documents")}
        </Text>
        {activeDocuments && activeDocuments.length > 0 && (
          <View className="bg-slate-100 px-2 py-1 rounded-md">
            <Text className="text-[10px] font-manrope-bold text-slate-500 uppercase">
              {activeDocuments.length} {tran("Files")}
            </Text>
          </View>
        )}
      </View>

      <View className="gap-4">
        {activeDocuments && activeDocuments.length > 0 ? (
          activeDocuments.map((doc) => {
            const fileInfo = getFileIcon(doc.file);
            return (
              <Pressable
                key={doc.id}
                disabled={downloadingId === doc.id}
                onPress={() => handleDownload(doc)}
                className="flex-row items-center justify-between p-4 rounded-2xl border border-slate-100 bg-white shadow-sm active:bg-slate-50"
              >
                <View className="flex-row items-center flex-1 pr-4">
                  <View
                    className={`w-12 h-12 rounded-xl ${fileInfo.bgColor} items-center justify-center`}
                  >
                    <fileInfo.icon size={22} color={primary.base} />
                  </View>
                  <View className="ml-4 flex-1">
                    <Text className="text-sm font-manrope-bold text-slate-900 leading-tight mb-0.5">
                      {tran(doc.title)}
                    </Text>
                    {doc.description ? (
                      <Text className="text-xs font-manrope-medium text-slate-500 line-clamp-1" numberOfLines={1}>
                        {tran(doc.description)}
                      </Text>
                    ) : (
                      <Text className="text-[10px] font-manrope-semibold text-slate-400 uppercase tracking-tight">
                        {tran("Click to view document")}
                      </Text>
                    )}
                  </View>
                </View>
                <View className="w-8 h-8 rounded-full bg-slate-50 items-center justify-center">
                  {downloadingId === doc.id ? (
                    <ActivityIndicator size="small" color="#475569" />
                  ) : (
                    <DownloadIcon size={16} color="#475569" weight="bold" />
                  )}
                </View>
              </Pressable>
            );
          })
        ) : (
          <View className="py-12 items-center justify-center bg-slate-50 rounded-3xl border border-dashed border-slate-200">
            <View className="w-16 h-16 rounded-full bg-white items-center justify-center mb-4 shadow-sm">
                <FileDashedIcon size={32} color="#94a3b8" weight="light" />
            </View>
            <Text className="text-slate-500 font-manrope-bold text-sm">
                {tran("No documents available")}
            </Text>
            <Text className="text-slate-400 font-manrope-medium text-xs mt-1">
                {tran("This project doesn't have any public files yet.")}
            </Text>
          </View>
        )}
      </View>
    </View>
  );
}
