// src/app/dashboard/files/[id]/page.tsx
import { getFileNodeById } from "@/data-access/file-nodes"; 
import { mapMetadata } from "@/lib/transformers";         
import { notFound } from "next/navigation";
import { 
  Box, Container, Typography, Paper, Grid, Divider, Stack, Button 
} from "@mui/material";
import DescriptionIcon from '@mui/icons-material/Description';
import PhotoIcon from '@mui/icons-material/Photo';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import Link from "next/link";

export default async function FileDetailPage(props: { 
  params: Promise<{ id: string }> 
}) {
  // 1. Unwrapping params for Next.js 15/16+
  const { id } = await props.params;

  // 2. Fetch data via DAL
  const file = await getFileNodeById(id);

  // 3. Check schema-correct property 'isFolder'
  if (!file || file.isFolder) {
    notFound();
  }

  // 4. Transform data for the UI
  const data = mapMetadata(file);
  
  // 5. Derived extension logic
  const extension = file.name.split('.').pop()?.toLowerCase();
  const isPDF = extension === 'pdf';

  // 6. Handle BigInt for Size
  const sizeKB = file.size ? (Number(file.size) / 1024).toFixed(2) : "0";

  return (
    <Container maxWidth="lg" sx={{ py: 4 }}>
      {/* Navigation back to dashboard */}
      <Link href="/dashboard" style={{ textDecoration: 'none' }}>
        <Button 
          startIcon={<ArrowBackIcon />} 
          sx={{ mb: 3 }}
        >
          Back to Dashboard
        </Button>
      </Link>

      <Paper elevation={3} sx={{ p: { xs: 3, md: 5 }, borderRadius: 4 }}>
        <Stack direction="row" spacing={2} alignItems="center" sx={{ mb: 3 }}>
          {isPDF ? (
            <DescriptionIcon sx={{ color: '#f44336', fontSize: 40 }} /> 
          ) : (
            <PhotoIcon sx={{ color: '#2196f3', fontSize: 40 }} />
          )}
          <Box>
            <Typography variant="h4" fontWeight="900">{file.name}</Typography>
            <Typography variant="body2" color="text.secondary">
              ID: {file.id}
            </Typography>
          </Box>
        </Stack>

        <Grid container spacing={4}>
          {/* Left Column: Core Info & Preview */}
          <Grid item xs={12} md={7}>
            <Typography variant="h6" gutterBottom fontWeight="bold">Summary</Typography>
            <Divider sx={{ mb: 2 }} />
            
            {data.textPreview && (
              <Box sx={{ bgcolor: 'grey.50', p: 2, borderRadius: 2, mb: 3, border: '1px solid #ddd' }}>
                <Typography variant="subtitle2" color="primary" gutterBottom sx={{ fontSize: '0.7rem', fontWeight: 'bold' }}>
                  DOCUMENT PREVIEW
                </Typography>
                <Typography variant="body2" sx={{ fontStyle: 'italic', color: 'text.secondary' }}>
                  "{data.textPreview}..."
                </Typography>
              </Box>
            )}

            <Stack spacing={2}>
              <Box>
                <Typography variant="caption" color="text.secondary">FILE TYPE</Typography>
                <Typography variant="body1" fontWeight="500">{data.type}</Typography>
              </Box>
              <Box>
                <Typography variant="caption" color="text.secondary">SIZE</Typography>
                <Typography variant="body1" fontWeight="500">{sizeKB} KB</Typography>
              </Box>
              {data.pageCount > 0 && (
                <Box>
                  <Typography variant="caption" color="text.secondary">PAGE COUNT</Typography>
                  <Typography variant="body1" fontWeight="500">{data.pageCount}</Typography>
                </Box>
              )}
              <Box>
                <Typography variant="caption" color="text.secondary">UPLOADED AT</Typography>
                <Typography variant="body1" fontWeight="500">
                  {new Date(file.createdAt).toLocaleString()}
                </Typography>
              </Box>
            </Stack>
          </Grid>

          {/* Right Column: Deep Metadata */}
          <Grid item xs={12} md={5}>
            <Typography variant="h6" gutterBottom fontWeight="bold">Extracted Attributes</Typography>
            <Divider sx={{ mb: 2 }} />
            <Stack spacing={1}>
              {Object.entries(file.metadata as Record<string, any> || {}).map(([key, value]) => (
                <Box key={key} sx={{ display: 'flex', justifyContent: 'space-between', py: 0.5, borderBottom: '1px solid #f0f0f0' }}>
                  <Typography variant="body2" color="text.secondary" sx={{ fontWeight: '500' }}>
                    {key}
                  </Typography>
                  <Typography variant="body2" sx={{ textAlign: 'right', pl: 2 }}>
                    {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                  </Typography>
                </Box>
              ))}
              {/* FIXED: Properly closed logic for empty metadata */}
              {Object.keys(file.metadata as object || {}).length === 0 && (
                <Typography variant="body2" color="text.secondary" sx={{ fontStyle: 'italic' }}>
                  No extra metadata extracted for this file.
                </Typography>
              )}
            </Stack>
          </Grid>
        </Grid>
      </Paper>
    </Container>
  );
}