// @mui
import { useEffect, useState } from 'react';
import { 
  Button, 
  Container, 
  Grid, 
  styled, 
  Typography, 
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Card,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem, 
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Checkbox,
 
} from '@mui/material';
// hooks
import useSettings from '../hooks/useSettings';
// components
import { PieChart, Pie, Cell, Tooltip, BarChart, Bar, XAxis, YAxis, Legend, ResponsiveContainer } from 'recharts';
import Page from '../components/Page';
import axios from '../utils/axios';
import useAuth from '../hooks/useAuth';
import SomethingUsage from '../sections/dashboard/SomethingUsage';
import { fCurrency } from '../utils/formatNumber';
import dayjs from "dayjs";
import {DesktopDatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { green, red } from "@mui/material/colors";
import MuiDialog from '@/components/MuiDialog';
import SearchIcon from "@mui/icons-material/Search";

// ----------------------------------------------------------------------
const COLORS = ['#229A16', '#919EAB', '#FF4842'];

// const performaDokterData = [
//   { name: 'Dr. John', Berhasil: 70, Gagal: 8, Abandon: 4 },
//   { name: 'Dr. Richard', Berhasil: 68, Gagal: 10, Abandon: 2 },
//   { name: 'Dr. Harman', Berhasil: 75, Gagal: 5, Abandon: 3 },
//   { name: 'Dr. Emma', Berhasil: 80, Gagal: 7, Abandon: 1 },
//   { name: 'Dr. tb', Berhasil: 80, Gagal: 7, Abandon: 1 },
//   { name: 'Dr. test', Berhasil: 80, Gagal: 7, Abandon: 1 },
//   { name: 'Dr. yayan', Berhasil: 80, Gagal: 7, Abandon: 1 },
//   { name: 'Dr. intan', Berhasil: 80, Gagal: 7, Abandon: 1 },
//   { name: 'Dr. fajri', Berhasil: 80, Gagal: 7, Abandon: 1 },
// ];

// Custom Tooltip
const CustomTooltip = ({ active, payload, label }) => {
  if (active && payload && payload.length) {
    const totalPasien =
      payload[0].value + payload[1].value + payload[2].value;
    return (
      <div style={{ background: "#000", color: "#fff", padding: "10px", borderRadius: "5px" }}>
        <p>{label}</p>
        <p>Total Pasien: {totalPasien}</p>
        <p>Berhasil: {payload[0].value}</p>
        <p>Gagal: {payload[1].value}</p>
        <p>Abandon: {payload[2].value}</p>
      </div>
    );
  }
  return null;
};

// Custom Tooltip
const CustomTooltipPie = ({ active, payload, startDate, endDate }) => {
  if (!active || !payload || payload.length === 0) return null;
  // Fungsi format tanggal ke "2 Jan 2025"
  const formatDate = (date) => {
    if (!date) return "N/A";
    return new Date(date).toLocaleDateString("id-ID", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  };
  return (
    <div style={{ background: "#000", color: "#fff", padding: "10px", borderRadius: "5px" }}>
       <p>{formatDate(startDate)} - {formatDate(endDate)}</p>
      <p>Status: {payload[0]?.name || "Tidak ada data"}</p>
      <p>Jumlah Pasien: {payload[0]?.value || 0}</p>
    </div>
  );
};



export default function Dashboard() {
  
const transaksiDataDefault = [
  { name: "Berhasil", value: 0, color: "#4CAF50" },
  { name: "Gagal", value: 0, color: "#F44336" },
  { name: "Abandon", value: 0, color: "#9E9E9E" },
];
  const { themeStretch } = useSettings();
  const [startDate, setStartDate] = useState(dayjs().startOf('month').format('YYYY-MM-DD'));
  const [endDate, setEndDate] = useState(dayjs().format('YYYY-MM-DD'));
  const [startDateDokter, setStartDateDokter] = useState(dayjs().startOf('month').format('YYYY-MM-DD'));
  const [endDateDokter, setEndDateDokter] = useState(dayjs().format('YYYY-MM-DD'));
  const [transaksiData, setTransaksiData] = useState(transaksiDataDefault);
  const [transaksiDataBar, setTransaksiDataBar] = useState([]);
  const [type, setType] = useState(0);
  const [status, setStatus] = useState(0);
  const [statusDokter, setStatusDokter] = useState(0);
  const [view, setView] = useState(["day", "month", "year"]);
  const [performaDokterData, setListPerformaDoctors] = useState([]);
  const [doctors, setListDoctors] = useState([]);
  const [selectedDoctors, setSelectedDoctors] = useState(doctors.map((doctor) => doctor.id)); // State untuk dokter yang dipilih
  

  const fetchData = async () => {
    try {
      const response = await axios.get(`dashboard/transaksi`, {
        params: {
          start_date: startDate,
          end_date: endDate,
          type,
          status
        }
      });
      if (response.data) {
        setTransaksiData(response.data);
      }
      if (type === 0) {
        setView(["day", "month", "year"]); // Urutan yang benar: day, month, year
      } else {
        setView(["month"]); // Hanya menampilkan bulan & tahun
      }
    } catch (error) {
      console.error('Error fetching transaksi data:', error);
    }
  };

  const fetchDataBar = async () => {
    try {
      const response = await axios.get(`dashboard/transaksi-bar-chart`, {
        params: {
          start_date: startDate,
          end_date: endDate,
          type,
          status
        }
      });
      if (response.data) {
        setTransaksiDataBar(response.data);
      }
      if (type === 0) {
        setView(["day", "month", "year"]); // Urutan yang benar: day, month, year
      } else {
        setView(["month"]); // Hanya menampilkan bulan & tahun
      }
    } catch (error) {
      console.error('Error fetching transaksi data:', error);
    }
  }

  const fetchListPerfomaDokter = async () => {
    try {
      const response = await axios.get(`dashboard/list-performa-dokter`, {
        params: {
          start_date: startDateDokter,
          end_date: endDateDokter,
          type,
          statusDokter,
          nIDDokter: selectedDoctors
        }
      } );
      if (response.data) {
        setListPerformaDoctors(response.data);
      }
    } catch (error) {
      console.error('Error fetching transaksi data:', error);
    }
  };

  
  const fetchListDokter = async () => {
    try {
      const response = await axios.get(`dashboard/list-dokter`);
      if (response.data) {
        setListDoctors(response.data);
      }
    } catch (error) {
      console.error('Error fetching transaksi data:', error);
    }
  };

  // Fetch data saat pertama kali halaman dimuat dan ketika filter berubah
  useEffect(() => {
    fetchData();
    fetchDataBar();
    // fetchListPerfomaDokter();
  }, [startDate, endDate, type, status]);

  // Fetch 
  useEffect(() => {
    fetchListPerfomaDokter();
  }, [selectedDoctors, startDateDokter, endDateDokter])

  useEffect(() => {
    fetchListDokter();
  }, []);

 
  // Performa dokter
  const [openDialog, setOpenDialog] = useState(false);
  const handleOpen = () => setOpenDialog(true);
 

  const getContent = () => {
    const [search, setSearch] = useState(""); // State untuk pencarian dokter

    // Filter dokter berdasarkan pencarian
    const filteredDoctors = doctors.filter((doctor) =>
      doctor.name.toLowerCase().includes(search.toLowerCase())
    );
  
    // Handle pilih satu dokter
    const handleSelectDoctor = (id) => {
      setSelectedDoctors((prev) =>
        prev.includes(id) ? prev.filter((docId) => docId !== id) : [...prev, id]
      );
    };
  
    // Handle pilih semua dokter
    const handleSelectAll = () => {
      if (selectedDoctors.length === doctors.length) {
        setSelectedDoctors([]);
      } else {
        setSelectedDoctors(doctors.map((doctor) => doctor.id));
      }
    };

    const handleCloseDialog = () => {
      setOpenDialog(false);
      setSelectedDoctors([]);
    }

    const handlePilihDokter = () => {
      setOpenDialog(false);
      console.log(selectedDoctors);
    }  
    return (
      <>
        {/* Search Bar */}
        <TextField 
          fullWidth
          variant="outlined"
          placeholder="Search Doctor"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          InputProps={{
            endAdornment: <SearchIcon />,
          }}
          sx={{ mb: 2, mt:2 }}
        />
  
        {/* Table Dokter */}
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>
                  <Checkbox
                    checked={selectedDoctors.length === doctors.length}
                    onChange={handleSelectAll}
                  />
                </TableCell>
                <TableCell>Kode</TableCell>
                <TableCell>Nama</TableCell>
                <TableCell>Status</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {filteredDoctors.map((doctor) => (
                <TableRow key={doctor.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedDoctors.includes(doctor.id)}
                      onChange={() => handleSelectDoctor(doctor.id)}
                    />
                  </TableCell>
                  <TableCell>{doctor.code}</TableCell>
                  <TableCell>{doctor.name}</TableCell>
                  <TableCell>
                    <Typography
                      sx={{
                        color: doctor.online === 1 ? green[500] : red[500],
                        fontWeight: "bold",
                      }}
                    >
                      {doctor.online === 1 ? "🟢 Online" : "🔴 Offline"}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
        <DialogActions>
            <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialog}>Cancel</Button>
                <Button color="primary"  variant="contained" onClick={handlePilihDokter}>Pilih</Button>
           
            
        </DialogActions>
      </>
    );
  };
  

  return (
    <Page title="Dashboard">
      <Container maxWidth="xl">
        <Typography variant="h3" component="h1" paragraph>
          Dashboard
        </Typography>

        {/* Jumlah Transaksi */}
        <Card sx={{ p: 3, mb: 3 }}>
          <Typography variant="h5" gutterBottom>
            Jumlah Transaksi
          </Typography>
          <Grid container spacing={3}>
            {/* Pilih */}
            <Grid item sm={3}>
              <FormControl fullWidth>
                <InputLabel>Tipe</InputLabel>
                <Select 
                value={type} 
                onChange={(e) => setType(e.target.value)}
                >
                  <MenuItem value="0">Harian</MenuItem>
                  <MenuItem value="1">Mingguan</MenuItem>
                  <MenuItem value="2">Bulanan</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item md={2}>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DesktopDatePicker
                  label="Start"
                  views={view} 
                  value={startDate}
                  inputFormat="dd/MM/yyyy"
                  onChange={(value) => {
                    if (!value) return; // Hindari error jika value null atau undefined
                    if (type == 0) {
                      setStartDate(value);
                    } else {
                      setStartDate(new Date(value.getFullYear(), value.getMonth(), 1));
                    }
                  }}
                  renderInput={(params) => <TextField {...params} variant="outlined" />}
                />
              </LocalizationProvider>
            </Grid>
            <Grid item md={2}>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
              <DesktopDatePicker
                label="End"
                views={view} 
                inputFormat="dd/MM/yyyy"
                value={endDate}
                onChange={(value) => {
                  if (!value) return; // Hindari error jika value null atau undefined
                  if (type == 0) {
                    setEndDate(value);
                  } else {
                    setEndDate(new Date(value.getFullYear(), value.getMonth(), 1));
                  }
                }}
                renderInput={(params) => <TextField {...params} variant="outlined" />}
              />
              </LocalizationProvider>
            </Grid>
            {/* Pilih Status */}
            <Grid item sm={3}>
              <FormControl fullWidth>
                <InputLabel>Status</InputLabel>
                <Select 
                  value={status} 
                  onChange={(e) => setStatus(e.target.value)}
                >
                  <MenuItem value="0">Semua</MenuItem>
                  <MenuItem value="1">Berhasil</MenuItem>
                  <MenuItem value="2">Abandon</MenuItem>
                  <MenuItem value="3">Gagal</MenuItem>
                </Select>

              </FormControl>
            </Grid>
            <Grid item xs={12} md={4}>
              <ResponsiveContainer width="100%" height={350}>
                <PieChart>
                  <Pie
                    data={transaksiData}
                    cx="50%"
                    cy="50%"
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ percent }) => `${(percent * 100).toFixed(0)}%`}
                  >
                    {transaksiData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltipPie startDate={startDate} endDate={endDate} />} />
                  <Legend />
                </PieChart>
              </ResponsiveContainer>
            </Grid>
            <Grid item xs={12} md={8}>
              <div style={{ width: "100%", overflowX: "auto" }}>
                <ResponsiveContainer width={1000} height={350}>
                  <BarChart
                    data={transaksiDataBar}
                    margin={{ top: 10, right: 30, left: 10, bottom: 10 }}
                  >
                    <XAxis
                      dataKey="date"
                      tickFormatter={(date) => date}
                    />
                    <YAxis />
                    <Tooltip content={<CustomTooltip />} />
                    <Legend />
                    <Bar dataKey="Berhasil" fill="#4CAF50" barSize={20} />
                    <Bar dataKey="Gagal" fill="#F44336" barSize={20} />
                    <Bar dataKey="Abandon" fill="#9E9E9E" barSize={20} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Grid>
          </Grid>
        </Card>

        {/* Performa Dokter */}
        <Card sx={{ p: 3 }}>
          <Typography variant="h5" gutterBottom>
            Performa Dokter
          </Typography>
          <Grid container spacing={3}>
            {/* Pilih Dokter*/}
            <Grid item sm={3}>
              <Button variant="contained" onClick={handleOpen}>
                Pilih Dokter
              </Button>
            </Grid>
            {/* Pilih */}
            <Grid item sm={3}>
              <FormControl fullWidth>
                <InputLabel>Tipe</InputLabel>
                <Select 
                value={type} 
                onChange={(e) => setType(e.target.value)}
                >
                  <MenuItem value="0">Harian</MenuItem>
                  <MenuItem value="1">Mingguan</MenuItem>
                  <MenuItem value="2">Bulanan</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item md={2}>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
                <DesktopDatePicker
                  label="Start"
                  views={view} 
                  value={startDateDokter}
                  inputFormat="dd/MM/yyyy"
                  onChange={(value) => {
                    if (!value) return; // Hindari error jika value null atau undefined
                    if (type == 0) {
                      setStartDateDokter(value);
                    } else {
                      setStartDateDokter(new Date(value.getFullYear(), value.getMonth(), 1));
                    }
                  }}
                  renderInput={(params) => <TextField {...params} variant="outlined" />}
                />
              </LocalizationProvider>
            </Grid>
            <Grid item md={2}>
              <LocalizationProvider dateAdapter={AdapterDateFns}>
              <DesktopDatePicker
                label="End"
                views={view} 
                inputFormat="dd/MM/yyyy"
                value={endDateDokter}
                onChange={(value) => {
                  if (!value) return; // Hindari error jika value null atau undefined
                  if (type == 0) {
                    setEndDateDokter(value);
                  } else {
                    setEndDateDokter(new Date(value.getFullYear(), value.getMonth(), 1));
                  }
                }}
                renderInput={(params) => <TextField {...params} variant="outlined" />}
              />
              </LocalizationProvider>
            </Grid>
            {/* Pilih Status */}
            <Grid item sm={2}>
              <FormControl fullWidth>
                <InputLabel>Status</InputLabel>
                <Select 
                  value={statusDokter} 
                  onChange={(e) => setStatusDokter(e.target.value)}
                >
                  <MenuItem value="0">Semua</MenuItem>
                  <MenuItem value="1">Berhasil</MenuItem>
                  <MenuItem value="2">Abandon</MenuItem>
                  <MenuItem value="3">Gagal</MenuItem>
                </Select>

              </FormControl>
            </Grid>
            <Grid item sm={12} marginTop={2}>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={performaDokterData}>
                  <XAxis dataKey="name" />
                  <YAxis />
                  <Tooltip />
                  <Legend />
                  <Bar dataKey="Berhasil" fill="#4CAF50" />
                  <Bar dataKey="Gagal" fill="#F44336" />
                  <Bar dataKey="Abandon" fill="#9E9E9E" />
                </BarChart>
              </ResponsiveContainer>
            </Grid>
          </Grid>

          {/* Dialog Pilih Dokter */}
          <MuiDialog
            title={{name: "Pilih Dokter"}}
            openDialog={openDialog}
            setOpenDialog={setOpenDialog}
            content={getContent()}
            maxWidth="xl"
          />
          
        </Card>
      </Container>
    </Page>
  );
}
