import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogActions from "@mui/material/DialogActions";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableRow from "@mui/material/TableRow";
import type { RecipeDetail } from "../types";

interface Props {
  open: boolean;
  recipe: RecipeDetail | null;
  onClose: () => void;
}

export default function RecipeDetailDialog({ open, recipe, onClose }: Props) {
  if (!recipe) return null;

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>{recipe.name}</DialogTitle>
      <DialogContent dividers>
        <Typography variant="subtitle1" gutterBottom>
          Level {recipe.level} – {recipe.category} – {recipe.crystal} Crystal
        </Typography>
        {recipe.key_item && (
          <Typography variant="body2" gutterBottom>
            Key Item: {recipe.key_item}
          </Typography>
        )}
        {recipe.subcrafts.length > 0 && (
          <Typography variant="body2" gutterBottom>
            Subcrafts: {recipe.subcrafts
              .map(([c, lvl]: [string, number]) => `${c} (${lvl})`)
              .join(", ")}
          </Typography>
        )}
        <Stack direction="row" spacing={4} sx={{ mt: 2 }}>
          <Stack>
            <Typography variant="h6">Ingredients</Typography>
            <Table size="small">
              <TableBody>
                {recipe.ingredients.map(([name, qty]: [string, number]) => (
                  <TableRow key={name}>
                    <TableCell>{name}</TableCell>
                    <TableCell align="right">{qty}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Stack>
          <Stack>
            <Typography variant="h6">HQ Yields</Typography>
            <Table size="small">
              <TableBody>
                {recipe.hq_yields.map((hq: [string, number] | null, idx: number) => (
                  <TableRow key={idx}>
                    <TableCell>HQ{idx + 1}</TableCell>
                    <TableCell>
                      {hq ? `${hq[0]} x${hq[1]}` : "—"}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </Stack>
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Close</Button>
      </DialogActions>
    </Dialog>
  );
}
