"use client";

import { useState } from "react";
import { Button, CircularProgress } from "@mui/material";
import SyncIcon from "@mui/icons-material/Sync";
import { DataGrid, GridColDef } from "@mui/x-data-grid";
import { syncOneDrive } from "./sync-actions";
import { useRouter } from "next/navigation";

interface DashboardViewProps {
  initialFiles: any[];
}

export default function DashboardView({ initialFiles }: DashboardViewProps) {
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleSync = async () => {
    setLoading(true);
    try {
      await syncOneDrive();
      // This tells Next.js to re-run the Server Component (page.tsx) 
      // and fetch the fresh data from Postgres
      router.refresh(); 
    } catch (error) {
      console.error("Sync failed:", error);
      alert("Failed to sync OneDrive");
    } finally {
      setLoading(false);
    }
  };

  const columns: GridColDef[] = [
    { field: "name", headerName: "File Name", width: 300 },
    { 
      field: "metadata", 
      headerName: "Type", 
      width: 120,
      valueGetter: (params) => params?.type || "Unknown"
    },
    { 
      field: "size", 
      headerName: "Size (MB)", 
      width: 120,
      valueGetter: (value) => value ? (Number(value) / 1024 / 1024).toFixed(2) : "0"
    },
    { field: "updatedAt", headerName: "Last Synced", width: 200 },
  ];

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button
          variant="contained"
          startIcon={loading ? <CircularProgress size={20} color="inherit" /> : <SyncIcon />}
          onClick={handleSync}
          disabled={loading}
        >
          {loading ? "Syncing..." : "Sync OneDrive"}
        </Button>
      </div>

      <div style={{ height: 600, width: "100%" }}>
        <DataGrid
          rows={initialFiles}
          columns={columns}
          pageSizeOptions={[10, 25, 50]}
          initialState={{
            pagination: { paginationModel: { pageSize: 10 } },
          }}
        />
      </div>
    </div>
  );
}