// pages/dashboard/BrandAssistant/LinkedBrand.tsx
import { Container, Box, TextField, InputAdornment, Stack, Checkbox, FormControlLabel, FormGroup, Typography, Button, Drawer, Divider, IconButton, RadioGroup, FormControl, Radio, InputLabel, Select, MenuItem, SelectChangeEvent, ListItemText, Card } from '@mui/material';
import { useEffect, useState } from 'react';
import Iconify from 'src/components/Iconify';
import Scrollbar from 'src/components/Scrollbar';
// routes
import { PATH_DASHBOARD } from '../../../routes/paths';
// hooks
import useSettings from '../../../hooks/useSettings';
// _mock_
import { _userCards } from '../../../_mock';
// layouts
import Layout from '../../../layouts';
// components
import Page from '../../../components/Page';
import HeaderBreadcrumbs from '../../../components/HeaderBreadcrumbs';
// sections
import { UserCard } from '../../../sections/@dashboard/user/cards';
// import { videos } from 'src/_mock/_video';
import VideoCard from 'src/sections/@dashboard/video/videoCard';
import { NAVBAR } from 'src/config';
///import { getAllVideo, getContractById, getAllBrand, getContractByIdV } from 'src/pages/APIs/api';
import { getAllVideo, getContractByIdV } from 'src/pages/APIs/MediaAssistantAPIs';
import { getAllBrand } from 'src/pages/APIs/BrandAssitantAPIs';
// import VideoCard from 'src/sections/@dashboard/video/videoCard';
import NextLink from 'next/link';
import Label from 'src/components/Label';
import { paramCase } from 'change-case';
import { Brand } from 'src/@types/video';
import DatePicker from '@mui/lab/DatePicker'; // Import DatePicker
import { LocalizationProvider } from '@mui/lab';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
// ----------------------------------------------------------------------
VideoLists.getLayout = function getLayout(page: React.ReactElement) {
return <Layout>{page}</Layout>;
};
// ----------------------------------------------------------------------
const FILTER_STATUS_OPTIONS = [
{ label: 'All', value: 'All' },
{ label: 'Nháp', value: 'Nháp' },
{ label: 'Chính', value: 'Chính' },
];
type VideoData = {
id: "string",
assignmentID: "string",
contractID: "string",
taskID: "string",
scriptID: "string",
title: "string",
draftVersionUrl:
"string"
,
finalVersionUrl:
"string"
,
status: "string";
thumbnailUrl: "string";
createdAt: "Date | string | number";
brandName?: string; // Add brandName to the type
};
export default function VideoLists() {
const { themeStretch } = useSettings();
const [isFilterOpen, setIsFilterOpen] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
const [selectedBrand, setSelectedBrand] = useState(['All']);
const [selectedStatus, setSelectedStatus] = useState('All');
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
const [videos, setVideos] = useState<VideoData[]>([]);
const [brands, setBrands] = useState<any[]>([]); // State to hold fetched brands
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchVideosWithBrandNames = async () => {
try {
const token = localStorage.getItem('accessToken');
if (token) {
// Fetch videos, contracts, and brands concurrently
const [videos, brands] = await Promise.all([
getAllVideo(token),
getAllBrand(token)
]);
const videosWithBrandsPromises = videos.map(async (video: VideoData) => {
const contract = await getContractByIdV(video.contractID, token);
if (contract) { // Ensure contract is not null before finding brand
const brand = brands.find((b: Brand) => b._id === contract.brandID);
return { ...video, brandName: brand?.brandName || 'Unknown Brand' };
} else {
return { ...video, brandName: 'Unknown Brand' }; // Handle missing contract
}
});
const videosWithBrands = await Promise.all(videosWithBrandsPromises);
setVideos(videosWithBrands);
setBrands(brands);
} else {
setError('No access token found. Please log in.');
}
} catch (err) {
setError('Failed to fetch data. Please try again later.');
console.error(err);
}
};
fetchVideosWithBrandNames();
}, [videos]);
// const uniqueBrands = Array.from(new Set(videos.map((video) => video.brand)));
const handleFilterOpen = () => {
setIsFilterOpen(true);
};
const handleFilterClose = () => {
setIsFilterOpen(false);
};
const handleBrandChange = (event: SelectChangeEvent<typeof selectedBrand>) => {
const {
target: { value },
} = event;
setSelectedBrand(
// On autofill we get a stringified value.
typeof value === 'string' ? value.split(',') : value
);
};
const handleStatusChange = (event: SelectChangeEvent<string>) => {
setSelectedStatus(event.target.value);
};
const handleResetAll = () => {
setSelectedBrand(['All']);
setSelectedStatus('All');
setSearchTerm('');
setSelectedDate(null);
};
const handleDateChange = (date: Date | null) => {
setSelectedDate(date);
};
const filteredVideos = videos.filter((video) => {
const matchesSearch = video.title.toLowerCase().includes(searchTerm.toLowerCase());
const matchesBrand = selectedBrand.includes('All') || selectedBrand.includes(video.brandName || '');
const matchesStatus = selectedStatus === 'All' || video.status === selectedStatus;
const [day, month, yearTime] = video.createdAt.split("/");
const [year, time] = yearTime.split(" ");
const createdAtDate = new Date(`${year}-${month}-${day}T${time}`);
const matchesDate = !selectedDate || (
createdAtDate.getFullYear() === selectedDate.getFullYear() &&
createdAtDate.getMonth() === selectedDate.getMonth() &&
createdAtDate.getDate() === selectedDate.getDate()
);
return matchesSearch && matchesBrand && matchesStatus && matchesDate;
});
const STATUS_COLOR_MAP: { [key: string]: 'error' | 'info' } = {
Nháp: 'error',
Chính: 'info',
};
return (
<Page title="Trợ lý truyền thông: Danh sách video">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Container maxWidth={themeStretch ? false : 'lg'}>
<HeaderBreadcrumbs
heading="Danh sách video"
links={[
{ name: 'Công việc', href: PATH_DASHBOARD.kanban },
// { name: 'Brand Assistant', href: PATH_DASHBOARD.brandAssistant.root },
{ name: 'Danh sách video' },
]}
/>
<Box>
<Container maxWidth="lg">
<Stack
spacing={2}
direction={{ xs: 'column', sm: 'row' }}
justifyContent="space-between"
sx={{ mb: 2 }}
>
<Typography style={{display:'flex'}}>
<Box sx={{ mb: 3 }}>
<TextField
placeholder="Tìm tiêu đề..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Iconify icon={'eva:search-fill'} />
</InputAdornment>
),
}}
/>
</Box>
<Box sx={{ mb: 3, marginLeft:'15px' }}>
<DatePicker
label="Ngày đăng"
value={selectedDate}
onChange={handleDateChange}
renderInput={(params) => <TextField {...params} />}
/>
</Box>
</Typography>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 3 }}>
<Button
disableRipple
color="inherit"
endIcon={<Iconify icon={'ic:round-filter-list'} />}
onClick={handleFilterOpen}
>
Chọn lọc
</Button>
</Box>
</Stack>
<Box sx={{ display: 'grid', gap: 3, gridTemplateColumns: { xs: 'repeat(1, 1fr)', sm: 'repeat(2, 1fr)', md: 'repeat(3, 1fr)' } }}>
{filteredVideos.map((video) => (
<Card sx={{ textAlign: 'Left' }}>
<NextLink key={video.id} href={PATH_DASHBOARD.mediaAssistant.view(paramCase(video.contractID))} passHref>
<Stack alignItems="left" sx={{ cursor: 'pointer', textDecoration: 'none', color: 'inherit' }}>
<Box sx={{ position: 'relative' }}>
{video.status && (
<Label
variant="filled"
color={STATUS_COLOR_MAP[video.status] || 'default'}
sx={{
top: 16,
right: 16,
zIndex: 9,
position: 'absolute',
textTransform: 'uppercase',
}}
>
{video.status}
</Label>
)}
<img src={video.thumbnailUrl} alt={video.title} style={{ width: '100%', aspectRatio: '16/9' }} />
</Box>
<Typography variant="subtitle1" sx={{ mt: 3, paddingBottom: '10px', paddingLeft: '15px', paddingRight: '15px' }}>
{video.title}
</Typography>
<Typography variant="body2" sx={{ color: 'text.secondary', paddingBottom: '10px', textAlign: 'left', paddingLeft: '15px' }}>
Thương hiệu: {video.brandName} <br />
Ngày đăng: {video.createdAt}
{/* ScriptID : {video.scriptID} */}
</Typography>
</Stack>
</NextLink>
</Card>
))}
</Box>
</Container>
<Drawer
anchor="right"
open={isFilterOpen}
onClose={handleFilterClose}
PaperProps={{
sx: { width: NAVBAR.BASE_WIDTH },
}}
>
<Stack
direction="row"
alignItems="center"
justifyContent="space-between"
sx={{ px: 1, py: 2 }}
>
<Typography variant="subtitle1" sx={{ ml: 1 }}>
Chọn lọc
</Typography>
<IconButton onClick={handleFilterClose}>
<Iconify icon={'eva:close-fill'} width={20} height={20} />
</IconButton>
</Stack>
<Divider />
<Scrollbar>
<Stack spacing={3} sx={{ p: 3 }}>
<Stack spacing={1}>
<Typography variant="subtitle1" style={{ paddingBottom: "10px" }}>Nhãn hiệu</Typography>
<FormControl>
<InputLabel id="brand-select-label">Nhãn hiệu</InputLabel>
<Select
labelId="brand-select-label"
id="brand-select"
multiple
value={selectedBrand}
onChange={handleBrandChange}
label="Nhãn hiệu"
renderValue={(selected) => selected.join(', ')}
MenuProps={{
PaperProps: {
style: {
maxHeight: 48 * 4.5, // 4.5 items
width: 250,
},
},
}}
>
<MenuItem value="All">
<Checkbox checked={selectedBrand.includes('All')} />
<ListItemText primary="All" />
</MenuItem>
{brands.map((brand) => ( // Map over fetched brands
<MenuItem key={brand._id} value={brand.brandName}>
<Checkbox checked={selectedBrand.includes(brand.brandName)} />
<ListItemText primary={brand.brandName} />
</MenuItem>
))}
</Select>
</FormControl>
</Stack>
<Stack spacing={1}>
<Typography variant="subtitle1">Status</Typography>
<FormControl>
<RadioGroup value={selectedStatus} onChange={handleStatusChange}>
{FILTER_STATUS_OPTIONS.map((option) => (
<FormControlLabel
key={option.value}
value={option.value}
control={<Radio />}
label={option.label}
/>
))}
</RadioGroup>
</FormControl>
</Stack>
</Stack>
</Scrollbar>
<Box sx={{ p: 3 }}>
<Button
fullWidth
size="large"
type="submit"
color="inherit"
variant="outlined"
onClick={handleResetAll}
startIcon={<Iconify icon={'ic:round-clear-all'} />}
>
Loại bỏ toàn bộ
</Button>
</Box>
</Drawer>
</Box>
</Container>
</LocalizationProvider>
</Page>
);
}