import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import {
    Box,
    Button,
    IconButton,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    TextField,
    Typography,
    useTheme
} from "@mui/material";
import { useState } from "react";
import AccountType from "../../components/Account";

const mockAccounts: AccountType[] = [
    { id: "1", name: "John Doe", email: "john.doe@example.com", status: "active" },
    { id: "2", name: "Jane Smith", email: "jane.smith@example.com", status: "inactive" },
    { id: "3", name: "Alice Johnson", email: "alice.johnson@example.com", status: "active" },
];

export default function AccountsInfo() {
    const theme = useTheme();

    const [accounts, setAccounts] = useState<AccountType[]>(mockAccounts);
    const [searchTerm, setSearchTerm] = useState<string>("");
    const [editMode, setEditMode] = useState<{ [key: string]: boolean }>({});

    const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
        setSearchTerm(event.target.value.toLowerCase());
    };

    const handleDelete = (id: string) => {
        setAccounts((prev) => prev.filter((account) => account.id !== id));
    };

    const handleToggleStatus = (id: string) => {
        setAccounts((prev) =>
            prev.map((account) =>
                account.id === id
                    ? {
                        ...account,
                        status: account.status === "active" ? "inactive" : "active"
                    }
                    : account
            )
        );
    };

    const handleEdit = (id: string, field: keyof AccountType, value: string) => {
        setAccounts((prev) =>
            prev.map((account) =>
                account.id === id ? { ...account, [field]: value } : account
            )
        );
    };

    const toggleEditMode = (id: string) => {
        setEditMode((prev) => ({
            ...prev,
            [id]: !prev[id]
        }));
    };

    const filteredAccounts = accounts.filter(
        (account) =>
            account.name.toLowerCase().includes(searchTerm) ||
            account.email.toLowerCase().includes(searchTerm)
    );

    return (
        <Box sx={{ color: theme.palette.text.primary }}>
            <Typography variant="h4" gutterBottom align="center">
                Accounts Management
            </Typography>

            <TextField
                label="Search Accounts"
                variant="outlined"
                fullWidth
                sx={{
                    mb: 2,
                    backgroundColor: theme.palette.background.paper,
                    '& input': {
                        color: theme.palette.text.primary
                    },
                    '& label': {
                        color: theme.palette.text.secondary
                    },
                    '& .MuiOutlinedInput-root': {
                        '& fieldset': {
                            borderColor: theme.palette.divider
                        },
                        '&:hover fieldset': {
                            borderColor: theme.palette.text.primary
                        },
                        '&.Mui-focused fieldset': {
                            borderColor: theme.palette.primary.main
                        }
                    }
                }}
                onChange={handleSearch}
            />

            <TableContainer
                component={Paper}
                sx={{
                    backgroundColor: theme.palette.background.paper,
                    color: theme.palette.text.primary
                }}
            >
                <Table>
                    <TableHead>
                        <TableRow>
                            {["ID", "Name", "Email", "Status", "Actions"].map((col) => (
                                <TableCell
                                    key={col}
                                    sx={{ color: theme.palette.text.primary, fontWeight: "bold" }}
                                >
                                    {col}
                                </TableCell>
                            ))}
                        </TableRow>
                    </TableHead>

                    <TableBody>
                        {filteredAccounts.map((account) => (
                            <TableRow key={account.id}>
                                <TableCell>{account.id}</TableCell>
                                <TableCell>
                                    {editMode[account.id] ? (
                                        <TextField
                                            value={account.name}
                                            onChange={(e) => handleEdit(account.id, "name", e.target.value)}
                                            variant="standard"
                                            InputProps={{
                                                sx: { color: theme.palette.text.primary }
                                            }}
                                        />
                                    ) : (
                                        account.name
                                    )}
                                </TableCell>
                                <TableCell>
                                    {editMode[account.id] ? (
                                        <TextField
                                            value={account.email}
                                            onChange={(e) => handleEdit(account.id, "email", e.target.value)}
                                            variant="standard"
                                            InputProps={{
                                                sx: { color: theme.palette.text.primary }
                                            }}
                                        />
                                    ) : (
                                        account.email
                                    )}
                                </TableCell>
                                <TableCell>{account.status}</TableCell>
                                <TableCell align="center">
                                    <IconButton color="error" onClick={() => handleDelete(account.id)}>
                                        <DeleteIcon />
                                    </IconButton>
                                    <Button
                                        variant="contained"
                                        color={account.status === "active" ? "warning" : "success"}
                                        onClick={() => handleToggleStatus(account.id)}
                                        sx={{ mx: 1 }}
                                    >
                                        {account.status === "active" ? "Set Inactive" : "Set Active"}
                                    </Button>
                                    <IconButton color="primary" onClick={() => toggleEditMode(account.id)}>
                                        <EditIcon />
                                    </IconButton>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
        </Box>
    );
}
